Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script -- How to terminate parent if child fails to execute

Tags:

linux

bash

shell

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
like image 334
RAJESHPODDER007 Avatar asked Apr 14 '14 05:04

RAJESHPODDER007


People also ask

How do you terminate a shell script if statement?

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.

How do you terminate a shell script in Unix?

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.

How do you abort in bash?

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.

How do you quit a shell?

To exit from the shell: At the shell prompt, type exit. Ta-da!


2 Answers

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.

Example 1

set -e
false                        # Exits
echo Not executed            # Not executed

Example 2

set -e
if false                     # Does not exit
then echo False is true
else echo False is false     # This is executed
fi
like image 91
Jonathan Leffler Avatar answered Oct 02 '22 16:10

Jonathan Leffler


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.

like image 36
John1024 Avatar answered Oct 02 '22 16:10

John1024