0

I want to save the exit status of the last ran command (in a file, in a variable, it doesn't really matter), but this must be done automatically in an interactive shell, manually running something like var=$? is not an option.

I decided to try to use PROMPT_COMMAND to accomplish this. Below you can see me proving that what I tried didn't work.

/home/exit_status$ export PROMPT_COMMAND="echo $?"                           
0                                                                   
/home/exit_status$ rm /                                                      
rm: cannot remove ‘/’: Is a directory                               
0                                                                   
/home/exit_status$ echo $?                                                   
1                                                                   
0

How do I go about making it so that the snippet above works as I intend? I can work out how to store it, I don't need help with that. I just mentioned that to give context.

4

Because you used double quotes, $? is getting expanded when you assign the value - as you can verify using set -x:

$ PROMPT_COMMAND="echo $?"
+ PROMPT_COMMAND='echo 0'
++ echo 0
0

If you change the double quotes to single quotes, you should get the desired behaviour:

$ PROMPT_COMMAND='echo $?'
+ PROMPT_COMMAND='echo $?'
++ echo 0
0

i.e.

$ set +x
+ set +x
0
$ ls nofile
ls: cannot access 'nofile': No such file or directory
2
  • Great! Works like a charm. – exit_status May 18 at 14:05
0

Just put it in a var after the command.

/home/exit_status$ export PROMPT_COMMAND="echo $?"                           
0                                                                   
/home/exit_status$ rm /                                                      
rm: cannot remove ‘/’: Is a directory                               
0                                                                   
/home/exit_status$ u=$?                                                   
0
/home/exit_status$ echo $u
1                                                
0
  • $u will host the status until reset.
  • you can't insert u=$? into PROMPT_COMMAND as $u will be overwriten by each command.
  • on a side note, I am unsure this will work in a script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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