Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
3  
you can use echo $? which is the return value of the last command executed –  Kiwy Mar 12 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 at 18:51

2 Answers 2

up vote 11 down vote accepted

Shells are built to do that sort of thing easily.

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

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
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. –  WinnieNicklaus Mar 12 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 $?
fi

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 at 13:21

Your Answer

 
discard

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.