2012年6月11日星期一

Colors & Prompts in BASH


Bourne Again Shell offers a lot of power, flexibility and fun. Many new Unix users do not realize the flexibility of the shell environment; indeed; many new Unix users regard the shell as primitive and too restricted: nothing could be further from the truth. With very little time investment a new Unix user can learn how not to just make their work environment in the shell more productive but even a little fun.
This text only discusses the bash shell and the latest versions of the bash shell.
In the old days (a few years ago...) shell prompts did not all act alike. Most earlier Unix shells did not react well to path munging, prompt changing or special characters. The modern Bash shell does not suffer issues like long path name buffer mangling, getting lost or not having enough built ins.

The Prompt

First and foremost to (most) users the shell prompt itself; there are 3 approaches to the shell prompt (in no particular order) for those who want to customize it:
  • Put pwd in the prompt (do not care about the rest).
  • A very sexy/l33t prompt (do not care about the rest).
  • A nice prompt and pwd crammed in there.
Addressing each point is easiest...

PWD

The basic method of changing a prompt is by modifying the PS1 variable:
[[email protected]:~]$ PS1="foo% "
foo% 
Bash has a builtin for handling the current working directory:
\w
On most Linux systems the current or print working directory sequence is already defined in /etc/profile:
[[email protected]:~]$ PS1="foo% "
foo% PS1="foo \w $"
foo ~ $cd docs
foo ~/docs $
So there is the pwd capability, now onto what can be done with the prompt string itself.

Pretty Prompts

By default, Bash prints whoami at (&) hostname if there is a default profile installed for Bash on the particular system. Bash uses some more built in sequences to do so:
if [ $PS1 ]; then
  if [ "$BASH" ]; then
    PS1='\[email protected]\h:\w\$ '
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi
Specifically, the \u and \h set the user and hostname. What most folks like, however, is to use interesting looking characters in the prompt. This is none to difficult to do:
PS1=":-) \h\w$ "
:-) vela~/www/systhread.net/texts$ 


To create a colorized prompt use the color names in the prompt where desired:
PS1="${BRIGHT_CYAN}[${CYAN}\[email protected]\h${WHITE}:\w${BRIGHT_CYAN}]${NORMAL}\$ ${RESET}"
Simple, functional and just a little fun.



  case "$TERM" in
  screen*|xterm*|rxvt*)
      PS1='\[\033[01;32m\]\[email protected]\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
      ;;
  *)
      PS1='\[email protected]\h:\w\$ '
      ;;
  esac

没有评论:

发表评论