Updated bash PS1

Made a minor tweak to my .bashrc after browsing dotfiles.org for some ideas. One neat trick I gleaned was detecting when the exit code of the last command ($?) was non-zero and altering the prompt. This will be useful for quickly seeing at a glance if some enormous load of output from make was successful or not.

Note the prompt goes red on failure

Note the prompt goes red on failure

Here are the bits from my updated .bashrc:

  1. # define useful aliases for color codes
  2. sh_norm="\[\033[0m\]"
  3. sh_black="\[\033[0;30m\]"
  4. sh_darkgray="\[\033[1;30m\]"
  5. sh_blue="\[\033[0;34m\]"
  6. sh_light_blue="\[\033[1;34m\]"
  7. sh_green="\[\033[0;32m\]"
  8. sh_light_green="\[\033[1;32m\]"
  9. sh_cyan="\[\033[0;36m\]"
  10. sh_light_cyan="\[\033[1;36m\]"
  11. sh_red="\[\033[0;31m\]"
  12. sh_light_red="\[\033[1;31m\]"
  13. sh_purple="\[\033[0;35m\]"
  14. sh_light_purple="\[\033[1;35m\]"
  15. sh_brown="\[\033[0;33m\]"
  16. sh_yellow="\[\033[1;33m\]"
  17. sh_light_gray="\[\033[0;37m\]"
  18. sh_white="\[\033[1;37m\]"
  19.  
  20. case `hostname` in
  21.     "livehost"|"production_server"|"sauron")
  22.         HOSTCOLOUR=${sh_red}
  23.         ;;
  24.     "staging-node")      HOSTCOLOUR=${sh_yellow} ;;
  25.     *)              HOSTCOLOUR=${sh_green} ;;
  26. esac
  27.  
  28. export PROMPT_COMMAND=‘if [ $? -ne 0 ]; then ERROR_FLAG=1; else ERROR_FLAG=; fi; ‘
  29. export PS1=${sh_white}\u@’${HOSTCOLOUR}\h${sh_norm}\w\n${sh_norm}‘${ERROR_FLAG:+’${sh_light_red}‘}\$${ERROR_FLAG:+’${sh_norm}‘} ‘



I’m also using the hostname to decide what colour the host appears in the prompt. My home directory, and thus .bashrc, is mounted on most hosts I log in to, and this serves as a reminder if I’m logged in to a production host. Green is the default, and it’s overridden for various special hosts.

Tags:

Saturday, October 11th, 2008 hacks

2 Comments to Updated bash PS1

  1. Something unexpected I noticed since my prompt does this: Run `top` then press `q` to quit – this exits with a non-zero code, which I found a bit strange.

  2. RJ on October 19th, 2008
  3. Have you tried fish instead of bash? Or htop instead of top (for the commenter).

  4. Steven Roussey on January 29th, 2009

Leave a comment