BASH – 使用陷阱ctrl c

前端之家收集整理的这篇文章主要介绍了BASH – 使用陷阱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
原文链接:https://www.f2er.com/bash/383872.html

猜你在找的Bash相关文章