Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

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

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?

share|improve this question
you can use echo $? which is the return value of the last command executed – Kiwy Mar 12 '14 at 12:44
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 '14 at 18:51
up vote 12 down vote accepted

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.

share|improve this answer
Except for grep and its variants, where 0 indicates match found, 1 indicates match not found ("failure"?), and codes higher than 2 indicate error. – WinnieNicklaus Mar 12 '14 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.

share|improve this answer
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 '14 at 13:21

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.