1

I've add a trap to my bash script so when CTRL+C is pressed a message appears Do you want to quit ? (y/n)

This works at most parts of the script, but fails at others.

I've created a simple example that shows it always failing.

#!/bin/bash

quit() {
echo "Do you want to quit ? (y/n)"
  read ctrlc
  if [ "$ctrlc" = 'y' ]; then
    exit
  fi
}

trap quit SIGINT
trap quit SIGTERM

while true; do
    echo -e "\n\e[91mIs everything done ? (y/n)\e[0m"
    read -i "y" -e yn
    case $yn in
        [Nn]* ) continue;;
        [Yy]* ) 

        echo -e "Done"
        break;;
        * ) echo -e "\e[91mPlease answer yes or no.\e[0m";;
    esac
done

Why when I press CTRL+C does this pop up Do you want to quit ? (y/n) but not allow me to exit ? How do I solve it ?

Thanks

Tom
  • 1,436
  • 24
  • 50

2 Answers2

1

The above code is running without any errors in bash shell. I suspect that you have run the script in dash SHELL (some machine's default SHELL is dash).

Run your script using the below methods,

/bin/bash

or

Give executing permission to your script file (chmod 777 script.sh) and run the file like below,

./script.sh

sprabhakaran
  • 1,615
  • 5
  • 20
  • 36
1

As I commented above - inside a function, exit is treated as a synonym for return and does not terminate a program. If that is your problem, try

kill -term $$ # send this program a terminate signal

instead of just exit. It's heavy-handed but generally effective.

Note that if you also have a SIGTERM trap that will be executed.

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36