boolean.is.null
boolean.is.null

Reputation: 881

Idle bash script until CTRL+c event is logged

I have a bash script which does some work, which is done fairly quick. It should then idle until the user decides to terminate it, followed by some clean-up code.

This is why I trap the CTRL+c event with the following code:

control_c()
{
  cleanup
  exit 0
}

trap control_c SIGINT

But as my script is done quite quickly I never get to purposely terminate it, so it never gets to trap the CTRL+c and run the clean-up code.

I figured I could implement an endless do while loop, with sleep at the end of the script, but I assume there is a better solution.

How can I idle a script in bash, expecting the CTRL+c event?

Upvotes: 9

Views: 11171

Answers (3)

user5507535
user5507535

Reputation: 1800

I had problem with read -r -d '' _ </dev/tty, I placed it in a script to prevent it from exiting and killing jobs. I have another script that uses dialog and calls the first one as a job, when the script reaches read -r -d '' _ </dev/tty the parent script dialog have a very weird behavior, like someone is constantly pressing the Esc key, this makes the dialog try to quit.

What I recommend is to use sleep you can sleep for a long time like 999 days sleep 999d and if you need for sure for it to never stop you wan put it in a while loop.

Upvotes: 1

Brent Bradburn
Brent Bradburn

Reputation: 54919

The following will wait for Ctrl-C, then continue running:

( trap exit SIGINT ; read -r -d '' _ </dev/tty ) ## wait for Ctrl-C
echo script still running...

Upvotes: 6

Charles Duffy
Charles Duffy

Reputation: 295500

Assuming you're connected to a TTY:

# idle waiting for abort from user
read -r -d '' _ </dev/tty

Upvotes: 14

Related Questions