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

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...