How to run multiple shell scripts one after another in 1 shell script

Hello Everyone,

I have 4 shell scripts each should run one after another and only if previous script successfully runs then next one should run. if any script got failed it should exit the sequence. how can
i achieve this? how to can i check if previous script is successful and how can trigger next one.
Please help me with this. Thanks in Advance.

Write a short "driver" script that calls each script and then checks for the completion status.

If status is pass, run the next script, otherwise exit. Repeat the same thing until either failure or all scripts are complete.

All proper script languages are capable of doing this.

Weclome @sarathnani,

you could use a loop:

#!/bin/bash

SCRIPTS="/a/b/foo.sh /c/d/bar.sh"

for scr in $SCRIPTS; do
    # call script and save stdout, stderr & return code
    out=$($scr 2>&1); rc=$?
    if [[ $rc != 0 ]]; then
        # write error msg to stderr, then exit
        echo "error $rc in script $scr: $out" >&2
        exit $rc
    fi
done
1 Like

We assume that "success" means a good exit status (0).
The most simple chaining of commands is

command1 &&
command2 &&
command3 &&
command4

The && only continues with the following command if the previous command had a good exit status.

5 Likes

Set the flag in the main script:

#!/bin/bash
set -e

Thank you for help mate. I'm running my commands/script from AWS Run-Command so my command's are like this listed below:

su - -c "/opt/db/dbadmin/script/test0.sh" db2isnt1
su - -c "/opt/db/dbadmin/script/test1.sh" db2isnt1

how can i pass these commands?

Hi @sarathnani,

you can either call the scripts in the loop via su, e.g.

PATH="/opt/db/dbadmin/script"
SCRIPTS=(
"test0.sh args ..."
"test1.sh args ..."
) # use array here due to the spaces in commands

for scr in "${SCRIPTS[@]}"; do
    out=$(su - -c "$PATH/$scr" 2>&1); rc=$?

But with this method you have to enter root's password on each call. It is simplier to call the script itself with su:

[[ $(id -u) != 0 ]] && { echo "$0: call me as root" >&2; exit 1; }
...
for scr in "${SCRIPTS[@]}"; do
    out=$($PATH/$scr 2>&1); rc=$?

and then

su - -c /path/to/wrapper.sh

/path/to/ is only needed if the script is not found in root's $PATH.

Another option is to use sudo, which only needs user's password instead of root's (in addition, the user has to be a member of the sudo group).

2 Likes

Since a su -c runs a shell, the following should work

su - -c "
/opt/db/dbadmin/script/test0.sh db2isnt1 &&
/opt/db/dbadmin/script/test1.sh db2isnt1
"
1 Like

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.