Search code examples
linuxbashjobs

How to run one bash script after the previous one has finished successfully?


I have three scripts Script1 - Deletes leftover files and copies new file for processing Script2 - Executes the cobol program for the newly copied files Script3 - Executes another cobol program for comparison and create a zip of the required output files.

Is there a way to execute them in the below order Script1 completed successfully, then execute Script2. If Script2 executed successfully, then execute Script3. If Script3 is complete, then send an email that the task is complete. If failure happens during execution of any script then, send an email about the script where the failure happened?

As of now, I am executing the scripts manually in the sequence and was looking for a way to automate the execution.

Here is the code that I tried but the execution sequence is getting messed up. Like script3 executed before script2 and I am sure that I am missing other checks as well

#!/bin/sh
#
nohup ./fgaudext1.sh >/data/shell/fgaud/log/nohup_fgaudext1.txt 2>&1 &
pid_1=$(pidof fgaudext1.sh)
wait ${pid_1}
nohup ./fgaudext2.sh >/data/shell/fgaud/log/nohup_fgaudext2.txt 2>&1 &
#
pid_2=$(pidof fgaudext2.sh)
wait ${pid_2}
nohup ./fgaudext3.sh >/data/shell/fgaud/log/nohup_fgaudext3.txt 2>&1 &
#
pid_3=$(pidof fgaudext3.sh)
wait ${pid_3}
#
echo "Recon complete for AUDIT files"


Solution

  • First, if bash use proper shebang. Then, you can exit with the value of the script that failed.

    #! /bin/bash
    for n in {1..3}; do
      /path/to/fgaudext${n}.sh >/data/shell/fgaud/log/nohup_fgaudext${n}.txt 2>&1 || exit $n
    done
    echo 'Send email'