Saturday, March 26, 2011

My Bash Profile - Part V: Prompt

This is what my prompt looks like:
Your Bash prompt is stored in the PS1 variable. In my prompt, I display the following items, colour coded where appropriate:
  • time (\t)
  • user (\u) - red if a production user, green otherwise
  • host (\H) - red if a production machine, green otherwise
  • working directory (_get_path) - trimmed to 80 characters
  • number of jobs currently running in the shell (\j)
  • history number of this command (\!)
  • exit status of the previous command (_get_exit_status) - green if success, red otherwise
I also have a useful function called title which allows me change my xterm's titlebar so that I can differentiate it from other xterm's.

Update: My dotfiles are now in Git. For the latest version, please visit my GitHub dotfiles repository.

Here is my prompt taken from ~/.bash_prompt.


# define some colours
GREY=$'\033[1;30m'
RED=$'\033[1;31m'
GREEN=$'\033[1;32m'
YELLOW=$'\033[1;33m'
BLUE=$'\033[1;34m'
MAGENTA=$'\033[1;35m'
CYAN=$'\033[1;36m'
WHITE=$'\033[1;37m'
NONE=$'\033[m'

# trims long paths down to 80 chars
_get_path(){
  local x=$(pwd | sed -e "s:$HOME:~:")
  local len=${#x}
  local max=80
  if [ $len -gt $max ]
  then
      echo ...${x:((len-max+3))}
  else
      echo ${x}
  fi
}

# prints a colour coded exit status
_get_exit_status(){
   local es=$?
   if [ $es -eq 0 ]
   then
       echo -e "${GREEN}${es}"
   else
       echo -e "${RED}${es}"
   fi
}

# change xterm title
title() {
   if [ $# -eq 0 ]
   then
      title=""
   else
      title="$* - "
   fi
}

# colour the host red if it is production
# all prod hostnames end with "prod"
if [[ $HOSTNAME =~ prod$ ]]
then
    HOST_COLOR=$RED
else
    HOST_COLOR=$GREEN
fi

# colour the user red if it is production
# all prod usernames end with "prod"
if [[ $USER =~ prod$ ]]
then
    USER_COLOR=$RED
else
    USER_COLOR=$GREEN
fi

#executed just before prompt
PROMPT_COMMAND='exitStatus=$(_get_exit_status);mydir=$(_get_path);'

PS1='\033]0;${title}\u@\h:`tty`>${mydir}\007\n\
\[${GREY}\][\[${BLUE}\]\t\[${GREY}\]]\
\[${GREY}\][\[${USER_COLOR}\]\u\[${GREY}\]@\[${HOST_COLOR}\]\H\[${GREY}\]] \
\[${WHITE}\]${mydir} \
\[${GREY}\](\
\[${YELLOW}\]+${SHLVL}\[${GREY}\]|\
\[${YELLOW}\]%\j\[${GREY}\]|\
\[${YELLOW}\]!\!\[${GREY}\]|\
\[${YELLOW}\]${exitStatus}\[${GREY}\])\[${NONE}\]\n\
\[${USER_COLOR}\]$\[${NONE}\] '

# continuation prompt
PS2='\[${USER_COLOR}\]>\[${NONE}\] '

#used by set -x for tracing
PS4='\[${USER_COLOR}\]+\[${NONE}\] '
References:

More posts on my Bash profile:

2 comments:

  1. Anonymous7:42 AM

    Excellent! The one thing I think is missing is the running time of the last command.

    ReplyDelete
  2. Latest version of https://github.com/xeor/ninjab supports running time of last command. Use it like it is or rip it out from https://github.com/xeor/ninjab/blob/master/parts/4_prompt :)

    ReplyDelete

Note: Only a member of this blog may post a comment.