Problem Statement:-
I have four shell script that I want to execute only when the previous script got executed successfully. And I am running it like this currently-
./verify-export-realtime.sh
sh -x lca_query.sh
sh -x liv_query.sh
sh -x lqu_query.sh
So In order to make other scripts run after previous script was successful. I need to do something like below? I am not sure whether I am right? If any script got failed due to any reason it will print as Failed due to some reason right?
./verify-export-realtime.sh
RET_VAL_STATUS=$?
echo $RET_VAL_STATUS
if [ $RET_VAL_STATUS -ne 0 ]; then
echo "Failed due to some reason"
exit
fi
sh -x lca_query.sh
RET_VAL_STATUS=$?
echo $RET_VAL_STATUS
if [ $RET_VAL_STATUS -ne 0 ]; then
echo "Failed due to some reason"
exit
fi
sh -x liv_query.sh
RET_VAL_STATUS=$?
echo $RET_VAL_STATUS
if [ $RET_VAL_STATUS -ne 0 ]; then
echo "Failed due to some reason"
exit
fi
sh -x lqu_query.sh
if you want more flexible of handling errors
That should be right. You can also print the error code if necessary by echoing the $ variable. You can also make your own return value codes by actually returning your own values in those scripts and checking them in this main one. It might be more helpful then "The script failed for some reason".
The shell provides an operator
&&
to do exactly this. So you could write:or you could get rid of the line continuations (
\
) and write it all on one lineIf you want to know how far it got, you can add extra commands that just set a variable:
The value of
$done
at the end tells you how many commands completed successfully.$?
will get set to the exit value of the last command run (which is the one that failed), or0
if all succeededAs @William Pursell said, your scripts really should report their own errors. If you also need error reporting in the calling script, the easiest way to do it is like this:
You can simply run a chain of scripts in the command line (or from other script), when the first failing command will break this chain, using "&&" operator:
And so on. The operation will break once one of the steps fails.
The standard way to do this is to simply add a shell option that causes the script to abort if any simple command fails. Simply write the interpreter line as:
or add the command:
(It is also common to do
cmd1 && cmd2 && cmd3
as mentioned in other solutions.)You absolutely should not attempt to print an error message. The command should print a relevant error message before it exits if it encounters an error. If the commands are not well behaved and do not write useful error messages, you should fix them rather than trying to guess what error they encountered. If you do write an error message, at the very least write it to the correct place. Errors belong on stderr: