Search code examples
bashwhile-loopsignals

Exit from while loop after catching signal


I'm writing a bash script to capture a signal from another program:

trap "echo Signal" SIGUSR1 
while :         
do
        sleep 1 
done
COMMAND 1
COMMAND 2
COMMAND 3
.........

I want to exit from the while loop after catching the signal, in order to launch COMMAND 1,2,3 and so on.

Any suggestions, please?


Solution

  • Put your commands in a function and then use the function in your trap:

    #!/bin/bash
    trap 'trp' SIGUSR1
    trp() {
            COMMAND 1
            COMMAND 2
            COMMAND 3
            ......... 
    }
    while :         
    do
        sleep 1        
    done