Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH - using trap ctrl+c

Tags:

bash

I'm trying to execute commands inside a script using read, and when the user uses Ctrl+C, I want to stop the execution of the command, but not exit the script. Something like this:

#!/bin/bash  input=$1 while [ "$input" != finish ] do     read -t 10 input     trap 'continue' 2     bash -c "$input" done unset input 

When the user uses Ctrl+C, I want it to continue reading the input and executing other commands. The problem is that when I use a command like:

while (true) do echo "Hello!"; done; 

It doesn't work after I type Ctrl+C one time, but it works once I type it several times.

like image 290
mar_sanbas Avatar asked Oct 07 '12 19:10

mar_sanbas


People also ask

How do I use 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 I interrupt in bash?

There are many methods to quit the bash script, i.e., quit while writing a bash script, while execution, or at run time. One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.


1 Answers

Use the following code :

#!/bin/bash # type "finish" to exit  stty -echoctl # hide ^C  # function called by trap other_commands() {     tput setaf 1     printf "\rSIGINT caught      "     tput sgr0     sleep 1     printf "\rType a command >>> " }  trap 'other_commands' SIGINT  input="$@"  while true; do     printf "\rType a command >>> "     read input     [[ $input == finish ]] && break     bash -c "$input" done 
like image 105
Gilles Quenot Avatar answered Oct 02 '22 17:10

Gilles Quenot