简体   繁体   English

如何防止用户使用 ctrl-c 停止脚本?

[英]How to prevent a user from using ctrl-c to stop a script?

I load a script in .bash_profile and this script will ask for right password whenever a user opens a terminal window.我在.bash_profile加载了一个脚本,每当用户打开终端窗口时,这个脚本都会要求输入正确的密码。 If the user enters a wrong code, the script will run exit to stop the current terminal.如果用户输入错误的代码,脚本将运行exit以停止当前终端。

if [ $code = "980425" ]; then
    echo hello
else
    exit
fi

But I realize that the user can always use ctrl - c to stop the script and enter the terminal.但是我意识到用户总是可以使用ctrl -c来停止脚本并进入终端。 How to avoid that?如何避免这种情况?

You can always trap SIGINT :你总是可以捕获SIGINT

trap 'echo got SIGINT' SIGINT

Once you're done, reinstall the default handler again with完成后,再次重新安装默认处理程序

trap SIGINT

See the POSIX spec for trap for details.有关详细信息,请参阅POSIX 规范以获取陷阱 This works in all Bourne shells, not just bash.这适用于所有 Bourne shell,而不仅仅是 bash。

You can use:您可以使用:

trap '' 2 
commands
trap 2

This disables signal 2 (control c) and then re-enables it after the command has run.这会禁用信号 2(控制 c),然后在命令运行后重新启用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM