Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Linux bash (or other shell.) Have you ever fat fingered "echo $?" into something like "echo $4" thereby permanently preventing you from knowing the return code for the previous command? I do this often (and it's so annoying), so I figured I'll ask: does bash and/or linux have a "return code stack" or array or something that holds the return codes from previous commands, not just the last one that you ran? I'm talking about simple commands not involving pipes.

share|improve this question
No. Probably because it isn't needed. I've never seen programmers adding such features just to mitigate fat fingers. – Michael Suelmann Oct 23 '13 at 22:26
Some people like to add that to their prompt. You might find that to meet your needs. – toppledwagon Oct 24 '13 at 0:14
Adding the exit code to my prompt is how I do it. It also saves me from having to echo $? manually. – Dennis Williamson Oct 24 '13 at 1:19
Now that's interesting. And if I'm keeping screen history (like in tmux or screen), then all I have to do is scroll up and find the command I'm interested in . I like it. – Michael Martinez Oct 24 '13 at 18:57

If you want to see return codes for interactive bash you can use the PROMPT_COMMAND variable like this:

    if [ $RC -ge 128 ]; then
        echo -e "Signal $SIG = $(kill -l $SIG)";
    if [ $RC -ne 0 ]; 
        then echo -n "! (RC=$RC)  "; 

The commands in this variable are executed after every command. It should only contain bash internal commands. In my example it shows the $? if it is not 0 and the signal if the previous command was killed by a signal.

share|improve this answer
Use lower case or mixed case variable names as a matter of habit in order to avoid possible name collision with shell variables. $[] for arithmetic operations is deprecated, use $(()) instead. In the case of your line, you can use (( sig = rc - 128 )). The only reason to avoid external commands in $PROMPT_COMMAND is that it might slow down the issuing of the prompt because of the short time it takes to spawn the command(s), but this can happen with poorly crafted Bash-only command sequences. Otherwise, external commands work just fine - try PROMPT_COMMAND=date for example. – Dennis Williamson Oct 24 '13 at 1:15
Also, in Bash, (( rc >= 128 )) is the preferred form for integer comparison. – Dennis Williamson Oct 24 '13 at 1:20
Also, the upper limit of signal numbers should be checked in order to avoid an error message. On my system that's 64 so: (( rc >= 128 && rc <= 192 )) – Dennis Williamson Oct 24 '13 at 2:06

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.