I've been playing around with some scripts of late to automate delivery of my various scripts and aliases 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 and partly to get some experience playing with C; like learning any language there's no substitute for diving right in by building something that no-one else will ever use!!
Here's the code - please be gentle this is my first outing in C. If you can spot any room for improvements then be sure to let me know in the comments.
To try this out grab pwdn.c and compile it for your system. (I've tested it out on linux and my mac and it works just fine)
To compile it:
gcc -o pwdn pwdn.c
If that worked a binary called pwdn will have been produced. Copy that somewhere in your path and then add the following to your .profile or .bashrc:
export PS1="\[\033[0;32m\]\u@\h \[\033[33m\]\$(pwdn 3)\[\033[0m\] \$ "
That's an example prompt feel free to adapt as required. The program defaults to the last two dirs and shows "..." in front of the dirs when the display is truncated. If there's only two dirs to show then you'll see them all. If you want more than 2 dirs just pass in a different number as the first argument.
Remember to source your .bashrc or .profile so that you see the changes.
Here's an example of the prompt in action:
muffin@shiva /Users/muffin $ cd ~/code/Python/Django
muffin@shiva .../Python/Django $
Just out of interest here's the same thing in python: