Reputation: 1618
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
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
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