Вы находитесь на странице: 1из 8

14/5/2014 Prompt Color | Taylor McGann's Blog

http://blog.taylormcgann.com/tag/prompt-color/ 1/8
TAG ARCHI VES: PROMPT COLOR
Customize Your Shell &
Command Prompt
Posted on 2012 June 13
As mentioned in a previous post, we received some new MacBooks and a Mac Mini at work.
Since most of my team prefers using PCs, I was able to get my hands on one. I immediately
noticed how different it was from the one I use at home, so I started customizing it right
away. I found I had forgotten how to do a couple things and it took me longer than I would
have liked to search the web, so Ive decided to dedicate a short post on how to customize
your shell and command prompt in Mac OS X.
If you use Linux or Windows (think cygwin or git bash) this may apply to you too. If you dont
use any sort of shell, well, then you might just want this for future reference.
Apps
Terminal is the default app that comes with Mac OS X. Another great app is iTerm 2 (Free). It
adds a lot of functionality that some users find lacking in Terminal.
General Preferences
Some programs that run the shell allow you to set the window size and buffer (essentially
scrolling inside the limitations of the window). This is really helpful to setup before hand since
lines that are too long will word wrap if you dont have a large window buffer. This will
inevitably happen at some point and its really annoying when it does, so take steps to
prevent it now.
If you find you navigate to a specific directory every time you open the shell, it may be a good
idea to tell the app to navigate to that directory when you open the shell. In Terminal, this can
be found at Preferences >> Settings >> Shell; in iTerm 2 this can be found at Preferences >>
Profiles >> General. There are a lot of other cool features (like window groupings) that you
Taylor McGann's Blog
A record of tech tips & tricks I stumble upon dailyand then some.
14/5/2014 Prompt Color | Taylor McGann's Blog
http://blog.taylormcgann.com/tag/prompt-color/ 2/8
should checkout.
Appearance
The next thing youre going to want to do is customize your shells color. I like the traditional
black background with white or light gray text and some colorful highlighting like green or
even just a plain grey.
For my shells font, I like to use Monaco 10pt. Smaller text lets me see more on the screen
since I usually only let my shell take up one half of the screen. I enable bold fonts and bright
colors for bold fonts, but I disable anti-aliasing (smooth edges) because I like that raw hacker
feel ;).
.profile, .bash_profile or .bashrc
Some of the most important customization takes place in the .profile file. Every time your shell
loads, it will run the commands found in the profiles. There are a number profiles some
system-wide (e.g. /etc/profile), others personal (e.g. .profile). The bash man page provides
useful information about the differences under the INVOCATION section:
Then at the bottom of the man page:
Whenbashisinvokedasaninteractiveloginshell,orasanon
interactiveshellwiththeloginoption,itfirstreadsandexecutes
commandsfromthefile/etc/profile,ifthatfileexists.After
readingthatfile,itlooksfor~/.bash_profile,~/.bash_login,and
~/.profile,inthatorder,andreadsandexecutescommandsfromthe
firstonethatexistsandisreadable.Thenoprofileoptionmaybe
usedwhentheshellisstartedtoinhibitthisbehavior.
Whenaloginshellexits,bashreadsandexecutescommandsfromthe
file~/.bash_logout,ifitexists.
Whenaninteractiveshellthatisnotaloginshellisstarted,bash
readsandexecutescommandsfrom/etc/bash.bashrcand~/.bashrc,if
thesefilesexist.Thismaybeinhibitedbyusingthenorcoption.
Thercfilefileoptionwillforcebashtoreadandexecutecommands
fromfileinsteadof/etc/bash.bashrcand~/.bashrc.
FILES
/bin/bash
Thebashexecutable
/etc/profile
Thesystemwideinitializationfile,executedforloginshells
/etc/bash.bashrc
Thesystemwideperinteractiveshellstartupfile
/etc/bash.bash.logout
Thesystemwideloginshellcleanupfile,executedwhenaloginshellexits
14/5/2014 Prompt Color | Taylor McGann's Blog
http://blog.taylormcgann.com/tag/prompt-color/ 3/8
In essence, .bash_profile is read upon login and .bashrc is read for each new shell opened
since you can have multiple shell sessions running at once without logging in again. In Mac
OS X, the .bash_profile overrides the .profile. Ive run into some problems with .profile in the
past, so Ive actually switched everything to .bash_profile.
The next four sections will discuss:
How to change prompt escapes (bash)
How to change prompt color (bash)
How to create your personal bin
How to create aliases
Change Prompt Escapes
First, I like to customize the prompte e. I cant stand it when the prompt is white and blends
in with the rest of the text in the shell. The appearance of the prompt is stored in the
environment variable $PS1. Try typing echo$PS1 in your shell. The text you see is a string
coded with the display setting for your shells prompt. It might look something like this:
\h:\W\u$
In this example, the \h represents the host computer, \W the working directory and \u the
current user. All this information makes sense if you were to use the CLI a lot. Back in the
old days, people would interface between various servers or computers over a network (esp.
in business scenarios). When youd change to a different server, youd want to know the
host computer you were accessing. Not all the computers had GUIs. Thus \h would let you
know which computer you were on; whether you were on yours or another.
The \u is common for similar reasons. Sometimes you use the su command to substitute
user and youll want to know which user you are acting as.
The \W should be self explanatory. You dont want to have to type pwd or ls all the time to
know where you are at in the file hierarchy.
In my prompt, Ive gotten rid of the host symbol (I dont switch hosts often and when I do,
the other prompt is usually different enough that I can tell Im on a different machine) and
~/.bash_profile
Thepersonalinitializationfile,executedforloginshells
~/.bashrc
Theindividualperinteractiveshellstartupfile
~/.bash_logout
Theindividualloginshellcleanupfile,executedwhenaloginshellexits
~/.inputrc
Individualreadlineinitializationfile
14/5/2014 Prompt Color | Taylor McGann's Blog
http://blog.taylormcgann.com/tag/prompt-color/ 4/8
replaced it with the history number prompt escape (\!). This escape lets you know which
number in the command history you have just typed. That way if you see a previous
command that youd like to repeat a couple lines up you just type !<number>. To view your
complete command history, type the command history. A simplified version of my prompt
looks like this:
\!\u:\W$
Heres a comprehensive list of prompt escapes to add to your prompt:
Change Prompt Color
To color code your prompt on a Mac, use the following template:
\a#anASCIIbellcharacter(07)
\d#thedatein"WeekdayMonthDate"format(e.g.,"TueMay26")
\D{format}#theformatispassedtostrftime(3)andtheresult
#isinsertedintothepromptstringanemptyformat
#resultsinalocalespecifictimerepresentation.
#Thebracesarerequired
\e#anASCIIescapecharacter(033)
\h#thehostnameuptothefirst'.'
\H#thehostname
\j#thenumberofjobscurrentlymanagedbytheshell
\l#thebasenameoftheshell'sterminaldevicename
\n#newline
\r#carriagereturn
\s#thenameoftheshell,thebasenameof$0(theportionfollowing
#thefinalslash)
\t#thecurrenttimein24hourHH:MM:SSformat
\T#thecurrenttimein12hourHH:MM:SSformat
\@#thecurrenttimein12houram/pmformat
\A#thecurrenttimein24hourHH:MMformat
\u#theusernameofthecurrentuser
\v#theversionofbash(e.g.,2.00)
\V#thereleaseofbash,version+patchlevel(e.g.,2.00.0)
\w#thecurrentworkingdirectory,with$HOMEabbreviatedwithatilde
\W#thebasenameofthecurrentworkingdirectory,with$HOME
#abbreviatedwithatilde
\!#thehistorynumberofthiscommand
\##thecommandnumberofthiscommand
\$#iftheeffectiveUIDis0,a#,otherwisea$
\nnn#thecharactercorrespondingtotheoctalnumbernnn
\\#abackslash
\[#beginasequenceofnonprintingcharacters,whichcouldbeused
#toembedaterminalcontrolsequenceintotheprompt
\]#endasequenceofnonprintingcharacters
14/5/2014 Prompt Color | Taylor McGann's Blog
http://blog.taylormcgann.com/tag/prompt-color/ 5/8
\[\033[COLOR_CODE_HERE\]PROMPT_ESCAPE_OR_TEXT_HERE\[\033[0m\]
Most Linux distributions use a little different format:
\e[COLOR_CODEPROMPT_ESCAPE\e[0m
The first portion before the desired prompt escape or text only begins painting the chosen
color (e.g., \[\033[1;34m\]). To stop painting a color, you have to reset to another color
or turn color off (e.g., \[\033[0m\]).
Here's a comprehensive list of color encoding:
#RegularColors
\[\033[0;30m\]#Black
\[\033[0;31m\]#Red
\[\033[0;32m\]#Green
\[\033[0;33m\]#Yellow
\[\033[0;34m\]#Blue
\[\033[0;35m\]#Purple
\[\033[0;36m\]#Cyan
\[\033[0;37m\]#White
#HighIntensty
\[\033[0;90m\]#Black
\[\033[0;91m\]#Red
\[\033[0;92m\]#Green
\[\033[0;93m\]#Yellow
\[\033[0;94m\]#Blue
\[\033[0;95m\]#Purple
\[\033[0;96m\]#Cyan
\[\033[0;97m\]#White
#Background
\[\033[40m\]#Black
\[\033[41m\]#Red
\[\033[42m\]#Green
\[\033[43m\]#Yellow
\[\033[44m\]#Blue
\[\033[45m\]#Purple
\[\033[46m\]#Cyan
\[\033[47m\]#White
#HighIntenstybackgrounds
\[\033[0;100m\]#Black
\[\033[0;101m\]#Red
\[\033[0;102m\]#Green
14/5/2014 Prompt Color | Taylor McGann's Blog
http://blog.taylormcgann.com/tag/prompt-color/ 6/8
\[\033[0;103m\]#Yellow
\[\033[0;104m\]#Blue
\[\033[10;95m\]#Purple
\[\033[0;106m\]#Cyan
\[\033[0;107m\]#White
#Replaceanyleadingleading0;with1;forboldcolors
#Replaceanyleading0;with4;tounderline
Once you've decided on the appropriate prompt add exportPS1="<customprompt>"
to your .profile. For example, this is what the line in my .profile looks like:
Add Personal "bin" to the PATH Variable
Every now and again you may want to create your own custom commands, scripts or
programs for the CLI. Instead of mixing these in with the rest of the OS's, just create your
own personal "bin" folder and add it to your PATH variable so that you can run those
commands from any folder in the shell.
exportPATH=$PATH:/Users/Taylor/bin
Create & Use Aliases
Aliases are really nifty. They can save you a lot of extra effort for frequently used and/or
lengthy commands. For example, I found that I liked to use lslhaG a lot more than just
ls as follows:
aliasls='lslhaG'
Alias long commands that you'd forget or never want to type. I use Git to version my code.
The gitlog command is very powerful and can include a lot of options. Instead of typing
the various options every time, I use an alias called glg:
Conclusion
At the end of the day, this is what my .bash_profile looks like:
UPDATED 2014-04-02
exportPS1="\[\033[1;34m\]\!\[\033[0m\]\[\033[1;35m\]\u\[\033[0m\]:\[\033[1;35m\]\W\[\033[0m\]$"
aliasglg='gitlogdateorderallgraphformat="%C(green)%h%Creset%C(yellow)%an%Creset%C(bluebold)%ar%Creset%C(redbold)%d%Creset%s"'
14/5/2014 Prompt Color | Taylor McGann's Blog
http://blog.taylormcgann.com/tag/prompt-color/ 7/8
##################
###MYALIASES###
##################
#gitcommandautocompletionscript
source~/bin/gitcompletion.bash
#gitcommamandssimplified
aliasgst='gitstatus'
aliasgco='gitcheckout'
aliasgci='gitcommit'
aliasgrb='gitrebase'
aliasgbr='gitbranch'
aliasgad='gitaddA'
aliasgpl='gitpull'
aliasgpu='gitpush'
aliasglg='gitlogdateorderallgraphformat="%C(green)%h%Creset%C(yellow)%an%Creset%C(bluebold)%ar%Creset%C(redbold)%d%Creset%s"'
aliasglg2='gitlogdateorderallgraphnamestatusformat="%C(green)%H%Creset%C(yellow)%an%Creset%C(bluebold)%ar%Creset%C(redbold)%d%Creset%s"'
#lsaliasforcolormode
aliaslh='lslhaG'
#lockcomputer
aliaslock='/System/Library/CoreServices/"MenuExtras"/User.menu/Contents/Resources/CGSessionsuspend'
#hibernationandsleepsettings
aliashibernate='sudopmsetahibernatemode25'
aliassleep='sudopmsetahibernatemode0'
aliassafesleep='sudopmsetahibernatemode3'
aliassmartsleep='sudopmsetahibernatemode2'
#up'n'folders
alias..='cd..'
alias...='cd../..'
alias....='cd../../..'
alias.....='cd../../../..'
#simpleip
aliasip='ifconfig|grep"inet"|grepv127.0.0.1|cutd\f2'
#moredetails
aliasip1="ifconfiga|perlnle'/(\d+\.\d+\.\d+\.\d+)/&&print$1'"
#externalip
aliasip2="curlshttp://www.showmyip.com/simple/|awk'{print$1}'"
#grepwithcolor
aliasgrep='grepcolor=auto'
#proxytunnel
#aliasproxy='sshDXXXXpXXXXUSER@DOMAIN'
#sshhome
14/5/2014 Prompt Color | Taylor McGann's Blog
http://blog.taylormcgann.com/tag/prompt-color/ 8/8
Proudly powered by WordPress
Share:
Like this:
Like
Be the first to like this.

What have you done to customize your shell or change your command prompt?
Posted in Technology | Tagged Bash, Bash Profile, Bashrc, CLI, Command Line
Interface, Command Prompt, Cygwin, iTerm, Linux, Mac OS X, Prompt Color,
Prompt Escape, Shell, Terminal | 12 Replies
#aliassshome='sshpXXXXUSER@DOMAIN'
#processes
#aliasps='psax'
#refreshshell
aliasreload='source~/.bash_profile'
###############################
###ENVIRONMENTALVARIABLES###
###############################
#AddhomebrewsbintoPATHvariable
exportPATH=$PATH:/usr/local/sbin
#AddpersonalbintoPATHvariable
exportPATH=$PATH:/Users/Taylor/bin#Mayberedundant;check~/.bash_profile,/etc/profile,/etc/paths,/etc/bashrc
#ShowdirtystateinpromptwheninGitrepos
exportGIT_PS1_SHOWDIRTYSTATE=1
#Changeprompt
PS1_OLD=${PS1}
exportPS1='\[\033[1;34m\]\!\[\033[0m\]\[\033[1;35m\]\u\[\033[0m\]:\[\033[1;35m\]\W\[\033[0m\]\[\033[1;92m\]$(__git_ps1"(%s)")\[\033[0m\]$'
Email Pocket Twitter 5 Facebook 1 Google LinkedIn

Вам также может понравиться