Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: infinite loop that is possible to quit



There's no real "good" or "bad" decision here until you start doing stuff inside that loop. How will immediately halting processing of that script cause trouble later? Will you corrupt data? Leave a peripheral in an unknown state? If there's no concern about data corruption, allowing Ctrl+C (or SIGTERM) terminate the processing of the script is fine.

Other options include:

1. Reading user input and looking for eg "q" being pressed
2. Looking for a specific file on the file system, eg ".stop" and stopping when that file appears
3. Looking for a specific file on the file system, eg "config" and stopping when that file disappears
4. Using a settings file which you watch for changes, reread the settings, and get the stop/go from a config settings
5. Catching Ctrl+C (SIGTERM) and handling it (more about that later)

    #!/bin/zsh
    
    CONTINUE=1
    
    wrap_up() {
        echo "Wrapping up."
        CONTINUE=0
    }
    
    trap 'wrap_up' HUP INT QUIT TERM
    
    while [ $CONTINUE -eq 1 ] ; do
        echo "I'm still here."
        sleep 5
    done

Which will produce something like:

    [user@host]$ ./traptest
    I'm still here.
    I'm still here.
    ^CWrapping up.

The traps I'm catching there are the ones usually associated with a soft shutdown.

HTH
HAND

> On 1 Dec 2020, at 12:50, Emanuel Berg <moasenwood@xxxxxxx> wrote:
> 
> How do I do an infinite loop that runs something, but it will
> still be possible to quit the whole thing?
> 
> The best thing I've come up with is
> 
> while true; do
>  # run program
>  sleep 1
> done
> 
> Then do, say, q to exit the program, and C-c during the sleep
> period to quit the loop!
> 
> Is this good or bad?
> 
> TIA
> 
> -- 
> underground experts united
> http://user.it.uu.se/~embe8573
> https://dataswamp.org/~incal
> 
> 





Messages sorted by: Reverse Date, Date, Thread, Author