Originally published at Dom's Blog. You can comment here or there.
The file ~/.bashrc can contain a definition of the variable PS1 which is used to determine the prompt used on a command line. Normally this would display the username, hostname, working directory and is often modified to include additional information such as the time of day the command completes, history number or exit code.
The exit code of a process is zero if the command has completed successfully, otherwise the number is determined by the application – these are normally documented in its manpage.
A function can be defined within the .bashrc file which prints different strings dependant upon the exit code of the previously executed application, and the prompt constructed to include this, but upon further testing an issue arises with the length of the line when the text being entered wraps, as the number of characters in the prompt is calculated incorrectly. The reason for this is that the escape codes used to change the colour within the prompt are assumed by bash to take up space, but in fact they do not. This can be worked-around by enclosing the variables expressing the colours in escaped square brackets, but the same is not true within the print command used within the exit-code dependant function – instead, the strings 01 and 02 are used to denote the non-printing colour changes:
if [ "$ret_val" = "0" ]
printf "\001$Red\002:(\001$Normal\002 ($ret_val)"
PS1="\[$Magenta\]\u@\h\[$Normal\]:\[$Cyan\]\w \$(smiley) \[$Normal\]"