2

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 Answers 2

    4

    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 
      2

      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.

        You must log in to answer this question.

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.