I don’t know how many of you have taken a good care of your shell prompt. I spent some time to develop my own one, it has Vim-like directory name abbreviation method and it displays the error code, which I learned from somewhere.

When the return code isn’t zero, the prompt will show the code in color white on red, right before the normal prompt, which is the current directory. (I recently removed username and hostname from it, it’s not useful to me.)

It’s good, but I have always felt the error code break the harmony. It just suddenly shows up out of blue, I love it and I also hate it. I love it because it tells me the program exits with an error. I hate it because I need to resolve the issue and the other reason is it breaks the left edge. It pushes my normal prompt. Well, it acts like a bully, “get out of my way, you poor directory name!”

I tried to put the error code on the right edge on the same line of new prompt line, but when I press Backspace to delete the last character, the error code got erased as well. I moved it to the line above, it looked so lonely.

So, I decided to give it its own line. Yes, it’s a bully, maybe it’s because it’s lack of attention?

http://farm6.static.flickr.com/5093/5449928497_9747abb701_z.jpg

Error code in its own line

Here is the diff and the complete bashrc:


diff -r c974d2e6a74c dotfiles/bashrc
--- a/dotfiles/bashrc Wed Feb 16 00:59:43 2011 +0800
+++ b/dotfiles/bashrc Wed Feb 16 16:44:46 2011 +0800
@@ -57,8 +57,8 @@

PS1_ERROR='$(
ret=$?
-(( ret == 0 )) && exit 0
-printf "\[\e[41;1;37m\][%3s]\[\e[0m\]" "$ret"
+(( ret == 0 )) ||
+printf "\e[41;1;37m%${COLUMNS}s\e[$(((COLUMNS-${#ret})/2))G%s\e[0m\n\[\e[0m\]" "" "$ret"
)'

if [[ $TERM == 'screen' ]]; then

I use printf built-in to fill the line and calculate the position to but the error code in the middle of line. You can see it resets colors twice and make sure the second one which is with normal prompt is wrapped with \[\]. You need that so your prompt won’t be messed up when you navigate through history commands.