I have a shell script that executes a number of commands. How do I make the shell script exit if any of the commands exit with a non-zero exit code?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
After each command, the exit code can be found in the
$?variable so you would have something like:You need to be careful of piped commands since the
$?only gives you the return code of the last element in the pipe so, in the code:will not return an error code if the file doesn’t exist (since the
sedpart of the pipeline actually works, returning 0).The
bashshell actually provides an array which can assist in that case, that beingPIPESTATUS. This array has one element for each of the pipeline components, that you can access individually like${PIPESTATUS[0]}:Note that this is getting you the result of the
falsecommand, not the entire pipeline. You can also get the entire list to process as you see fit:If you wanted to get the largest error code from a pipeline, you could use something like:
This goes through each of the
PIPESTATUSelements in turn, storing it inrcif it was greater than the previousrcvalue.