1

I have a bash script runs a command in an infinite while loop. The script looks something like:

while :
do
     python3 my_program.py
done

Is there a simple way to terminate this while loop from the terminal in a way that doesn't interrupt the python process? ie the python process will finish, then the loop terminates.

Stated another way, perhaps: Is there a while loop whose termination condition is some terminal input?

2

You can trap SIGINT in your script and set a loop exit condition. Running your program with setsid prevents it from receiving SIGINT from CTRL+C

#! /bin/bash

STOPFILE=/tmp/stop_my_program

rm -f $STOPFILE

trap "touch $STOPFILE" INT

while [ ! -f $STOPFILE ]
do
     setsid python3 my_program.py
done

rm -f $STOPFILE
1

You could background the process and then wait on the process to complete before starting the next loop. This would allow you to kill the loop without killing the python process.

while : ; do
  python3 my_program.py &
  while true; do
    kill -0 %1 || break
    sleep 1
  done
done

Then just C-C (ctrl-c) to interrupt the loop.

kill -0 means don't really kill, but exit with a failing code if there's nothing to (not) kill.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.