Tom
Tom

Reputation: 1618

BASH Trap CTRL+C Then Exit Script Completely

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

Upvotes: 2

Views: 5625

Answers (2)

Paul Hodges
Paul Hodges

Reputation: 15246

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.

Upvotes: 1

sprabhakaran
sprabhakaran

Reputation: 1635

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

Upvotes: 1

Related Questions