25 Nov 2007 mathrick   » (Journeyer)

More useful bash prompt

Working on a project with a rather deep directory hierarchy, I finally got tired of my prompt overflowing the line and wrapping around. So, here’s a handy <code>bash</code> function to put in your <code>$PS1</code>. It should be noted that I did not write it, I only wrapped it up in a function and added some aesthetic options, but all the hard work and <code>bash</code> hackery was done by BearPerson from <code>#bash</code>.

# Produces the same effect as \w in $PS1, but makes sure that the
# result length doesn't exceed $1 chars. If any dirs are omitted, they
# are replaced with [...]. Optional $2 turns on ANSI VT100 escape
# sequences to dim the [...] part. Optional $3 specifies the colour
# code to dim to (otherwise 02, "dim")
bound_pwd ()

    pre=$([ $ansi ] && echo -n "\[\033[${colour}m\]")
    suf=$([ $ansi ] && echo -n "\[\033[0m\]")

    [[ $CANDIDATE =~ $regex ]]

    echo $CANDIDATE

To use it, either put it in your <code>.bashrc</code>, or in a file that is sourced by <code>.bashrc</code>, then replace <code>\w</code> in your <code>$PS1</code> with <code>$(bound_pwd)</code>. Personally I use <code>$(bound_pwd 25 1)</code> to get at most 25 chars, with VT100 colour codes.

Obligatory screenshot:

Bash prompt with the shortening

<s>Update: If you use VT100 colours, remember to surround the <code>bound_pwd</code> invocation with <code>\[ \]</code>, otherwise non-printing characters will confuse <code>bash</code> and make it wrap lines incorrectly</s>

Update 2: The above update was wrong. It’s actually more complex than that, and due to the fact that <code>bash</code> doesn’t exactly have coherent escaping semantics, I had to rework the function. If you use VT100 colours and have downloaded an earlier version of bound_pwd, you have to download it again, it has changed. Additionally, to have it really work, you have to add this function:

set_ps1 ()
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:'"$(bound_pwd 25 1)"'$ '

And in <code>.bashrc</code>, add this:

# Yes, it's silly that ; alone is not valid syntax

Make sure it’s the last line to set <code>PROMPT_COMMAND</code>. Especially if you’re on Debian/Ubuntu, as their default <code>.bashrc</code> sets it conditionally.


Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!