所以我试图创建一个脚本,为用户提供一些操作选项,其中一个选项是退出脚本。但是,我想阻止用户使用Control c
退出脚本,以便退出的唯一方法是选择正确的选项。是否可以制作脚本,以便当用户点击control c
时,程序不会退出,而是会echo
"enter 0 to exit"
之类的内容?
#!/bin/bash
# Acts as a simple administration menu
OPTION=0
echo "-----------------Admin Menu-------------------"
echo "Please select one of the following options: "
echo ""
echo "1 - Run top."
echo "2 - Show system uptime."
echo "3 - Show logged in users."
echo "4 - Exit Menu."
echo "5 - Reprint this menu."
echo "----------------------------------------------"
echo "Please choose an option (5 to reprint menu):"
read OPTION
while [ "$OPTION" -ne 4 ]
do
if [ "$OPTION" -eq 1 ]; then
clear
top -n1
elif [ "$OPTION" -eq 2 ]; then
clear
uptime
elif [ "$OPTION" -eq 3 ]; then
clear
who
elif [ "$OPTION" -eq 4 ]; then
clear
OPTION=4
elif [ "$OPTION" -eq 5 ]; then
clear
echo "------------COSC 2306 Admin Menu--------------"
echo "Please select one of the following options: "
echo ""
echo "1 - Run top."
echo "2 - Show system uptime."
echo "3 - Show logged in users."
echo "4 - Exit Menu."
echo "5 - Reprint this menu."
echo "----------------------------------------------"
else
clear
echo "ERROR: Incorrect Input."
fi
echo "Please choose an option (5 to reprint menu):"
read OPTION
done
clear
答案 0 :(得分:4)
您可以使用内嵌trap
来抓住SIGINT
(ctrl
+ C
生成信号SIGINT
)并打印您的消息:
trap 'echo "enter 0 to exit"' SIGINT
同样,您也可以捕获其他信号。要获取信号列表,请使用kill -l
。