Start script after another one (already running) finishes
LinuxBashProcessLinux Problem Overview
So I have a process running, and it will take several hours to complete. I would like to start another process right after that one finishes, automatically. Notice that I can't add a call to the second script in the first one, neither create another which sequentially runs both. Is there any way to do this in Linux?
Edit: One option is to poll every x
minutes using pgrep and check if the process finished. If it did, start the other one. However, I don't like this solution.
PS: Both are bash scripts, if that helps.
Linux Solutions
Solution 1 - Linux
Given the PID of the first process, the loop
while ps -p $PID; do sleep 1; done ; script2
should do the trick. This is a little more stable than pgrep and process names.
Solution 2 - Linux
Maybe you can press ctrl+z first and enter
fg; echo "first job finished"
Solution 3 - Linux
Polling is probably the way to go, but it doesn't have to be horrible.
pid=$(ps -opid= -C your_script_name)
while [ -d /proc/$pid ] ; do
sleep 1
done && ./your_other_script
Solution 4 - Linux
You can wait
already running process using bash built-in command wait
. man bash.
> wait [n ...] Wait for each specified process and return its > termination status. Each n may be a process ID or a job specification; > if a job spec is given, all processes in that job's pipeline are > waited for. If n is not given, all currently active child processes > are waited for, and the return status is zero. If n specifies a > non-existent process or job, the return status is 127. Otherwise, the > return status is the exit status of the last process or job waited > for.
Solution 5 - Linux
Often it happens that your program is running several demons. In that case your pid will be an array. Just use:
> PID=($(pidof -x process_name)) #this saves all the PIDs of the given process in the $pid array
Now, just modify the thiton's code as :
while ps -p ${PID[*]}; do sleep 1; done ; script2
Solution 6 - Linux
I had a similar problem and solved it this way:
nohup bash script1.sh &
wait
nohup bash script2.sh &
Solution 7 - Linux
I had the same requirement and solved it in the following way:
while [[ "$exp" != 0 ]]; do
exp=$(ps -ef |grep -i "SCRIPT_1" |grep -v grep |wc -l)
sleep 5;
done
call SCRIPT_2
Solution 8 - Linux
The easiest way:
./script1.sh && ./script2.sh
The && says wait for the successful completion of script1 before proceeding to script2.