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.
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.
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”.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With