Showing last two directories of pwd in BASH prompt | Comments (4)
Posted in Code, Linux/Unix on 25th September 2007, 5:01 pm by Stuart
I’m working on a project where we are using Bazaar downstream of CVS and we have several common Bazaar branches for keeping up to date with CVS. The problem with this is that you can be in the first directory of the branch who’s name is exactly the same another branch. Now you can run pwd to know where you are, but this is a pain when you quickly want to know which branch you are currently looking at.
To solve the problem I decided instead of displaying the last directory of the working directory path with \W, if I could look at the last two directories then that would be enough to know which branch I’m working from. There is another alternative which is to show the full working path (\w) in the prompt but that would drive me crazy as I hate long prompts. Also having this information in the prompt suits me better than displaying the full path in the title bar for example.
To that end I’ve added a custom function to get the last two directories from pwd and to dynamically display it in my prompt. To use this add the following to your .bashrc file. Don’t forget to source your .bashrc file (source ~/.bashrc) to see the changes.
function PWD {
pwd | awk -F\/ '{print $(NF-1),$(NF)}' | sed 's/ /\\//'
}
export PS1="\\e]2;\\h \\W\\a\\033[32;1m\\]\\033[0;32m\\]\u@\\h \[\\033[33m\\`PWD\\`\\033[0m\\]\$ “;

Great function in code, thanks from Poland
You can achieve this in C Shell (csh, tcsh) by adding the following statement to your .cshrc file:
set prompt = "%c2 # "or
set ellipsis = 1set prompt = "%c02 # "
Cool trick!
As a challenge to myself, I decided to rewrite this PWD function using only Bash built-ins after learning of parameter substitution. It actually does work! Here’s the resulting code, if you’re interested:
function PWD {
tmp=${PWD%/*/*};
[ ${#tmp} -gt 0 -a "$tmp" != "$PWD" ] && echo ${PWD:${#tmp}+1} || echo $PWD;
}
[...] and alias to servers and in doing so I was looking back at the code I am calling to display the last two directories in my bash prompt. It made me think; why don’t I write a command in C to do that for me? Partly for the lulz [...]