BASH – 使用陷阱ctrl c
发布时间:2020-12-16 01:32:46 所属栏目:安全 来源:网络整理
导读:我正在尝试使用read来执行脚本中的命令,当用户使用Ctrl C时,我想停止执行命令,但不要退出脚本. 这样的事情 #!/bin/bashinput=$1while [ "$input" != finish ]do read -t 10 input trap 'continue' 2 bash -c "$input"doneunset input 当用户使用Ctrl C时,我
我正在尝试使用read来执行脚本中的命令,当用户使用Ctrl C时,我想停止执行命令,但不要退出脚本.
这样的事情 #!/bin/bash input=$1 while [ "$input" != finish ] do read -t 10 input trap 'continue' 2 bash -c "$input" done unset input 当用户使用Ctrl C时,我希望它继续读取输入并执行其他命令.问题是当我使用如下命令: while (true) do echo "Hello!"; done; 在我输入Ctrl C一次之后,它不起作用,但是一旦输入了几次,它就会起作用.
您需要在不同的进程组中运行该命令,最简单的方法是使用作业控制:
#!/bin/bash # Enable job control set -m while : do read -t 10 -p "input> " input [[ $input == finish ]] && break # set SIGINT to default action trap - SIGINT # Run the command in background bash -c "$input" & # Set our signal mask to ignore SIGINT trap "" SIGINT # Move the command back-into foreground fg %- done (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |