10.12. Making PWD Pretty

Bash allows some pattern matching and substitution with variable names. This can be utilized to do some substitutions to make the output of ${PWD} look prettier. If you want to use it in combination with other modifications to PWD mentioned in the previous section, do those first.

PS1='${PWD//\//\[\033[1;37m\]/\[\033[1;36m\]}\[\033[1;37m\]> \[\033[0m\]'

This looks ugly, but is fairly straight forward. The basic principle is using pattern matching to replace all "/" characters in ${PWD}. Watch this in action by typing echo ${PWD//\//@} in a terminal. The first "//" means "do all replacements every time the pattern is found (not just once)." Next, since we're trying to match a "/", we have to escape it with a "\". Then another "/" to indicate that what follows is the replacement text, and then the "@" which is the replacement. The output will look something like "@home@giles". So what goes into the PS1 string above for the PWD replacement are just colour codes around a slash. The end product is your ${PWD} in bold cyan separated by white slashes and followed by a white ">". Note that this is inside single quotes which protect against the shell trying to do any parameter expansion: you can do it in double quotes, but then you have to backslash-escape some (but not all!) of the backslashes.

Relative speed: on an unloaded 800MHz Celeron, this takes negligible time.