0

There is a shell script:

#!/bin/bash
python3 do_something_1.py
python3 do_something_2.py
python3 do_something_3.py
python3 do_something_4.py
python3 do_something_5.py

If it's running python3 do_something_3.py now.

How can I tell bash process that after python3 do_something_3.py exits by itself(don't kill subprocess, wait it), no longer run subsequent commands python3 do_something_4.py,python3 do_something_5.py anymore?

5
  • python3 do_something_3.py && exit 0? Commented Aug 31, 2021 at 3:54
  • script already running, change script file may not work.
    – Bin Zhou
    Commented Aug 31, 2021 at 3:58
  • there is no possibility then knowing if python3 do_something_3.py failed of succeed out of your script (you may only can verify if it had given output as you were expected then go ahead and kill your running script), other than that you needed error handling in your script beforehand. Commented Aug 31, 2021 at 4:03
  • I want bash process wait python3 do_something_3.py subprocess normally exit (don't send signal to kill the subprocess), once the child process exits, skip the subsequent commands like 4.py & 5.py .
    – Bin Zhou
    Commented Aug 31, 2021 at 5:02
  • you are going in a wrong way, work on error handling in your script at first place Commented Aug 31, 2021 at 8:33

2 Answers 2

1

You can use a while loop to check if do_something_3.py is still running (e.g. using pgrep) and sleep as long it is.

After the loop, kill your script.

while pgrep -f do_something_3.py >/dev/null ; then
    sleep 0.1
done && pkill -9 myscript
  • The exact pkill command depends how you named and called the script, you might want to test it with pgrep myscript or find out the PID and use kill -9 PID.
  • Note, that this is nowhere ideal, because you won't find the exact timing to stop your script before do_something_4.py has started.
1

Signals are the simplest solution here. From the Bash man page:

If bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes.

An example (thescript.sh):

trap 'echo "Exiting on USR1 after command"; exit' USR1

echo 'Beginning'
sleep 2  # long-running command
echo 'Middle'
sleep 2  # long-running command
echo 'End'

This will exit after the first sleep completes:

./thescript.sh &
pid="$!"
sleep 1
kill -USR1 "$pid"  # roughly the middle of first sleep
wait -n "$pid"

This will exit after the second sleep completes:

./thescript.sh &
pid="$!"
sleep 3
kill -USR1 "$pid"  # roughly the middle of second sleep
wait -n "$pid"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .