I have a shell script (parent) which is calling some other shell script. Suppose a child shell script fails to execute, then the parent shell script should also be stopped without executing the next child shell script. How can I automate this process?
Ex:
main.sh
//inside the main.sh following code is there
child1.sh //executed successfully
child2.sh //error occurred
child3.sh //Skip this process
//end of main.sh
To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.
exit-Issuing the exit command at the shell prompt will cause the shell to exit. In some cases, if you have jobs running in the background, the shell will remind you that they are running and simply return you to the command prompt. In this case, issuing exit again will terminate those jobs and exit the shell.
This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.
To exit from the shell: At the shell prompt, type exit. Ta-da!
The simplest mechanism is:
set -e
This means that the shell will exit whenever a child process exits with a fail status unless the status is tested as part of a conditional.
set -e
false # Exits
echo Not executed # Not executed
set -e
if false # Does not exit
then echo False is true
else echo False is false # This is executed
fi
child1.sh && child2.sh && child3.sh
In the above child2.sh is executed only if child1.sh completes successfully and child3.sh is executed only if child2.sh completes successfully.
Alternatively:
child1.sh || exit 1
child2.sh || exit 1
child3.sh || exit 1
In the above, the parent script exits after any of the children fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With