Emulating tcsh's %c in bash

by: Mike Heffner | posted: August 26th, 2009

With tcsh you can set your prompt to include the %c[[0]n] escape character. The %c will print the current working directory with at most ‘n’ trailing components. This is similar to PROMPT_DIRTRIM in recent versions of bash, but IMO, better. In tcsh, the %c escape can optionally include a component to signify how many directories were actually trimmed off the beginning of the prompt.

For example, the escape %c03 if you were in a directory /etc/sysconfig/networking/profiles/default would expand to: /<2>networking/profiles/default. It also respects $HOME as a start point, so the directory $HOME/work/svn/cdc/scripts would expand to: ~/<1>svn/cdc/scripts.

Jeremie Le Hen has created an excellent emulation of this functionality for bash using only builtins. Below is an expanded version of Jeremie’s that should maintain the “~” when under $HOME and handle directory names with spaces.

Use it as: PS1="\$(traildir 3 \"\$PWD\")" to get a maximum of three trailing directories.