I have a bash file with commands to merge pcap files. I want to know if there is anyway to make sure a line in bash runs or not. Like in windows bat file we have %ErrorLevel% ¨ Say a command

touch -r dcn_file "${dir_dcn}"/"${TAG1_dcn}".pcap 

How do I make sure this was run?

  • 3
    you can use echo $? which is the return value of the last command executed
    – Kiwy
    Mar 12, 2014 at 12:44
  • 1
    You can also use set -e to make bash exit on failure automatically. You can also assign additional code using trap to be executed in case of error (or just at the end regardless of errors)
    – Vi.
    Mar 12, 2014 at 18:51

2 Answers 2


Shells are built to do that sort of thing easily.

if touch -r dcn_file "${dir_dcn}"/"${TAG1_dcn}".pcap 
    echo "Command ran successfully."
    echo "Command had an error: $?"

You will occasionally find some proprietary command that doesn't exit with 0 status on success and non-zero on failure, but thankfully, those abberations have almost gone extinct.

  • 1
    Except for grep and its variants, where 0 indicates match found, 1 indicates match not found ("failure"?), and codes higher than 2 indicate error. Mar 12, 2014 at 15:38

The bash variable $? hold the exit status of the last command run. For typical programs, the value 0 is success and any other value is failure. Specific return code should be documented in the man pages of the programs in question.

You can use code like:

touch -r dcn_file "${dir_dcn}"/"${TAG1_dcn}".pcap
[ $? -ne 0 ]; then
   echo "Command failed: touch: $?"
   return $?

To test the return code and then print an error message and have a script exit with the same error code.

  • As I read some documentation about nice this morning, the command could return the value of niceness of the process instead of 0 on old version
    – Kiwy
    Mar 12, 2014 at 13:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .