Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interrupt sleep in bash with a signal trap

Tags:

bash

shell

I'm trying to catch the SIGUSR1 signal in a bash script that is sleeping via the sleep command:

#!/bin/bash  trap 'echo "Caught SIGUSR1"' SIGUSR1  echo "Sleeping.  Pid=$$" while : do     sleep 10     echo "Sleep over" done 

The signal trap works, but the message being echoed is not displayed until the sleep 10 has finished.
It appears the bash signal handling waits until the current command finished before processing the signal.

Is there a way to have it interrupt the running sleep command as soon as it gets the signal, the same way a C program would interrupt the libc sleep() function?

like image 806
John Morris Avatar asked Dec 29 '14 19:12

John Morris


People also ask

How do you sleep for 5 seconds in bash?

How to Use the Bash Sleep Command. Sleep is a very versatile command with a very simple syntax. It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number.

How do you sleep 10 seconds in shell script?

/bin/sleep is Linux or Unix command to delay for a specified amount of time. You can suspend the calling shell script for a specified time. For example, pause for 10 seconds or stop execution for 2 mintues. In other words, the sleep command pauses the execution on the next shell command for a given time.

What is bash sleep command?

In other words, the sleep command pauses the execution of the next command for a given number of seconds. The sleep command is useful when used within a bash shell script, for example, when retrying a failed operation or inside a loop.


1 Answers

#!/bin/bash  trap 'echo "Caught SIGUSR1"' SIGUSR1  echo "Sleeping.  Pid=$$" while : do    sleep 10 &    wait $!    echo "Sleep over" done 
like image 59
Hans Klünder Avatar answered Sep 30 '22 10:09

Hans Klünder