user7319905
user7319905

Reputation:

how to exit from running if any one of script fails?

I am running club.sh

inside club.sh script i am running below scripts.

test1.sh test2.sh test3.sh

my concern is it should run one by one and if test1 fails it will not run test2.sh and if test2.sh fails it willnot run test3.sh

how can we check? can any one suggest any idea it would be very helpful.

Thanks,

Upvotes: 0

Views: 1052

Answers (4)

andre luiz
andre luiz

Reputation: 1

You just have to put the below at the begging of the script:

#!/bin/bash -e 

Upvotes: 0

Lix
Lix

Reputation: 47986

Two approaches -

First, you can examine the exit code of each of your inner scripts (test1.sh, test2.sh, ...) and decide whether to continue accordingly -

$? Will return the exit code of the previous command. It will be 0 (zero) if the script exited without an error. Anything that is not 0 can be considered a failure. So you could so something like this -

./test1.sh # execute script
if [[ $? != 0 ]]; then exit; fi # check return value, exit if not 0

Alternatively, you could use the && bash operator which will only execute subsequent commands if the previous one passed -

./test1.sh && ./test2.sh && test3.sh 

Only if test1.sh returns an exit code of 0 (zero) will test2.sh execute and the same goes for test3.sh.


The first approach is good if you need to do some logging or cleanup between executing your scripts, but if you are only concerned that the execution should not continue if there was a failure then the && method would be they way I recommend.


Here is a related post dealing with the meaning behind &&

Upvotes: 4

yoones
yoones

Reputation: 2474

If you want to exit your script whenever a command fails, you just add at the beginning of your script set -e.

#!/bin/bash

set -e

echo hello
ls /root/lalala
echo world

Otherwise, you have two options.

The first one is to use &&. For instance:

echo hello && ls /some_inexistant_directory && echo world

The second one is to check the return value after each command:

#!/bin/bash

echo toto
if [ "$?" != "0" ]; then
    exit 1
fi

ls /root
if [ "$?" != "0" ]; then
    exit 1
fi

echo world
if [ "$?" != "0" ]; then
    exit 1
fi

Upvotes: 2

Amani Ben Azzouz
Amani Ben Azzouz

Reputation: 2565

The returned value of the execution of the first command/script is stored in $? so using this value you can check if your command was successfully executed.

Try this:

bash test1.sh
if [ $? -eq 0 ]; then # if script succeeded
    bash test2.sh
else
    echo "script failed"
fi

Upvotes: 1

Related Questions