Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 593
boolean.is.null Avatar asked May 02 '16 21:05

boolean.is.null


People also ask

How do you Ctrl C in bash?

When you hit Ctrl + c , the line discipline of your terminal sends SIGINT to processes in the foreground process group. Bash, when job control is disabled, runs everything in the same process group as the bash process itself. Job control is disabled by default when Bash interprets a script.

How do you prevent Ctrl C cause the termination of a running bash script?

How do I disable Control-C? You need to use the trap command which can enable or disable keyboard keys such as Crtl-C. SIGINT is Crtl-C and it is represented using number 2. Signal names are case insensitive and the SIG prefix is optional.

How do I ignore Ctrl C in Linux?

Show the signal numbers with “kill -l”. In the below output the numbers for the signals are shown, and in case of CRTL+C is “SIGINT” signal number 2 and CRTL+Z is “SIGTSTP” signal number 20. To disable ctrl+c or ctrl+z for all users, append the trap command combinations in /etc/profile.


2 Answers

Assuming you're connected to a TTY:

# idle waiting for abort from user
read -r -d '' _ </dev/tty
like image 117
Charles Duffy Avatar answered Sep 21 '22 04:09

Charles Duffy


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...
like image 20
Brent Bradburn Avatar answered Sep 21 '22 04:09

Brent Bradburn