When you have a main shell script but inside it you call other shell scripts, let’s call then
A.sh, B.sh and C.sh. All are successful and their exit codes are all equal to zero. However, when you look into the output file of the first script which is A, it contains an error message. In your logic sequence the other scripts should not run if
A.sh has an error, now how you exit the main script and not to continue running the other shell scripts after the script that has output error?
When you call a command by the shell script on Linux Mint, Linux Ubuntu or others Unix like, the script has an exit status. Exit status is an integer number where
0 (zero) exit status means the command was successful without any errors. A non-zero (1-255 values) exit status means command was a failure.
Even if some command in your first bash script results in an error, the script as a whole may complete with
exit code 0.
This means that your sequence os scripts will not to be interrupted and you can check the exit code of any individual command in your script, maybe by using the
$? variable. This variable stores the exit code of the previous command. This will allow you to check for errors within the script.
This is a particular shell variable called
$? to get the exit status of the previously executed command. For example to print
$? variable use the echo command or printf command:
who echo $? wo echo $?
The output would be
mazer@mazer$ who mazer tty7 2022-11-04 13:26 (:0) mazer@mazer$ echo $? 0 mazer@mazer$ wo wo: command not found mazer@mazer$ echo $? 127
How to use the exit status of the command in a shell variable? You can do this assigning
$? to a shell variable. The syntax could be:
## 1. Run the who command ## cmd="who" $cmd ## 2. Get exist status and store into '$status' variable ## status=$? ## 3. Test it and take a decision based upon '$status' ## [ $status -eq 0 ] && echo "$cmd successful" || echo "$cmd failed"
Now we get back to our original problem that is to interrupt a main shell script if it has errors, wthout calling a sequence of scripts.
To do this, we gonna teste the
$? shell script last error variable, just after some commands that we know an exit error status can occur.
An example would be:
#!/bin/bash # # Sample shell script to check exit code status # ## rsync a local folder with a remote server ## rsync --delete -arzhD --stats -e "ssh -p 999 -i ~/.ssh/id_rsa" ./www/ [email protected]:/home/my-remote-user/www/ ## Did rsyn could run without any errors? ## if [ $? -eq 0 ] then echo "Success: Sync finished." exit 0 else echo "Failure: An error has occurred please check the server connection" >&2 exit 1 fi
You can stop your bash shell scripts when exit status has errors, avoiding a sequence of unsuccessful commands to be called, also improving you time and productivity fixing this errors earlier with correct output messages from your shell scripts.