Friday, September 22, 2006

Geeky Friday: Shorter directory path in command prompt

Gina Trapani, editor over at, has been diving deep into cygwin and command line goodness for a while. Earlier this week, she posted an article about customizing the command prompt. I added a comment about my shorter directory path, but I'll replicate here, because I have better control over the formatting of the code (and, I guess, for the people who read me, but not lifehacker):

I sometimes find having the full directory path in the prompt to be overwhelming, so I've created this small bash function which shows just the last two parts of the path:

short_dir ()
    if [ "$PWD" = "$HOME" ]; then
        echo '~'
        the_dir=`dirname "$PWD"`;
        the_base=`basename "$PWD"`;
        the_dir_base=`basename "$the_dir"`;
        if [ "$the_dir_base" = '/' ]; then
        echo "$the_dir_base/$the_base"

Add a call to this to your prompt, don't forget to escape the backquotes:

export PS1="\`short_dir\`\$ "

So, if your current directory is /usr/local/man/man1, your prompt would look like:


You can, of course, sprinkle in other bash prompt special characters, such as "\h" for the hostname:

export PS1="(\h) \`short_dir\`\$ "

produces: (myhost) man/man1$


Anonymous said...

Sorry, does your example contain a typo? Should not it be:
export PS1="\`short_dir\`\$ "

(and/or the funcion be called "myprompt" instead of "short_dir")

Doug said...

Ah, good catch. I've edited the post to fix the example.

As I was preparing this, I refactored a little. Previously the function was called "myprompt" and generated the full string of the prompt. I decided that I should let bash natively handle what it already handled well and my function should just generate the shorter path... and I changed the name to reflect this... but I didn't refactor my examples.