Bash prompt: how to have the initials of directory path

bashbashrccommand line

I normally have just the name of the current directory in my bash prompt (PS1='\u@\h:\W$ '), so if I am in ~/projects/superapp/src/ I get:

hamish@host:src$ 

However I'd like to have an indication of the full path without having the full path. I've seen screenshots where people would have

hamish@host:~/p/s/src$ 

if in the example directory above. So what value of PS1 would give that? Or failing that, what script do I need in my .bashrc to produce that?

Best Answer

Ok, I got curious, so here's one solution:

  1. First, create a function using a slight tweak of William Pursell's answer to the SO question I link in my comment above.
  2. Next, put that in your $PS1 as \$(function_name) in the appropriate place.

As an example:

short_pwd() {
    cwd=$(pwd | perl -F/ -ane 'print join( "/", map { $i++ < @F - 1 ?  substr $_,0,1 : $_ } @F)')
    echo -n $cwd
}
# later in your .bashrc
PS1="\u \$(short_pwd) \$ "

I'm hopeful that someone more skilled in Bash-scripting than I am can suggest ways to clean up the function, but this should give you some idea of how to use the output of another command (or Bash function) in a prompt. See also here: http://www.linux.org/docs/ldp/howto/Bash-Prompt-HOWTO/x279.html

Based on your comment, I looked again and realized that my solution needs to be double quoted. If you single-quote such a function, then it will not function at all.