Create interrupt in bash using keys like ENTER or ESC

I need to know if it is possible to interrupt a bash script with keys like ESC

or ENTER

? By submitting SIGINT /CTRL + C

I can do this, but for some reason (check the note on the last line) I cannot use CTRL +C

. So I need to have some custom way to trigger the interrupt.

In other words: When the script is clicked, the function cleanup

is called when clicked CTRL + C

. Now we need to change this behavior so that the function is cleanup

called when certain ENTER

OR keys are pressed ESC

.

cleanup() {

#do cleanup and exit
echo "Cleaning up..."
exit;

}
echo "Please enter your input:"
read input

    while true
        do
          echo "This is some other info MERGED with user input in loop + $input"
          sleep 2;
          echo "[Press CTRL C to exit...]"
          trap 'cleanup'  SIGINT
        done

      

Query:

  • Is it possible to use custom keys to invoke interrupts in bash?
  • If possible, how to achieve it?

Note:

Reason: This script is called from another C ++ program that has its own hook handling. So the handling of the hooks of this script is contrary to the parent program and eventually the terminal hangs itself. In my organization, this code is frozen, so I cannot change its behavior. I only have to customize this child script.

+3


source to share


2 answers


Here's a dirty trick that works great for my job. <key> read

and case

are the key. Here I am disabling the command read

, so as long as true continues unless the esc

or button is pressed enter

.



cleanup() {

#do cleanup and exit
echo "Cleaning up..."
exit;

}

exitFunction()

{
echo "Exit function has been called..."
exit 0;
}
mainFunction()
{
    while true
        do
          echo "This is some other info MERGED with user input in loop"
          IFS=''
          read -s -N 1 -t 2 -p  "Press ESC TO EXIT or ENTER for cleanup" input
          case $input in
                $'\x0a' ) cleanup; break;;
                $'\e'   ) exitFunction;break;;
                      * ) main;break;;
          esac
        done
}

mainFunction

      

0


source


The following works ^ M for ENTER and ^ [for ESC, but may

stty intr ^M 
stty intr ^[ 

      

but after cannot use ENTER to restore to default

stty intr ^C

      



After commenting, since the shell is interactive, you can also clear the hook in the special EXIT hook to ask to continue using the hook.

How do I prompt for Yes / No / Cancel input in a Linux shell script?

or another solution using select

echo "Do you want to continue?"
PS3="Your choice: "

select number in Y N;
do
    case $REPLY in
    "N")
        echo "Exiting."
        exit
        ;;
    "Y")
        break
        ;;
    esac
done
# continue

      

+1


source







All Articles