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.
#!/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
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).