Wednesday, July 7, 2010

Bash prompt custom substitution

I know this is only eye candy but sometimes LONG prompts do bother me.
If you ever got disturbed by too-long bash prompts that span over the entire terminal window in such a way that the commands you write go directly to the second line -- sometimes even a simple "ls" -- here is the solution.

1. Problem:
Your shell sometimes looks like:


2. Solution:
Open up your .bashrc (I'm assuming ubuntu but this should work everywhere) and paste the following to the end (I say at the end so it overrides any other ugly stuff you might have there!).

my_bash_prompt() {
case "$PWD" in

"/home/cpscotti/big_name_dir/huge_name_subdir/divide_and_conquer/little_one")
PS1='${debian_chroot:+($debian_chroot)}@SOMEBETTERNAME~\$ '
;;
"/home/cpscotti/big_name_dir/huge_name_subdir/divide_and_conquer/another")
PS1='${debian_chroot:+($debian_chroot)}@SOMEEVENBETTERNAME~\$ '
;;
*)
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
;;
esac

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\w\a\]$PS1"
;;
*)
;;
esac
}
PROMPT_COMMAND=my_bash_prompt
unset bash_prompt


Substitute the big directories for whatever suits you and change SOMEBETTERNAME and SOMEEVENBETTERNAME for something fancy and you're done! The real trick is to set PROMPT_COMMAND to call your function and do this "PWD abstraction" before displaying PS1. This is very similar to what the shell already does with your home folder, changing its path to ~ (tilde).

Ok, back to work!

No comments: