【问题标题】:BASH - using trap ctrl+cBASH - 使用陷阱 ctrl+c
【发布时间】:2012-10-07 19:07:22
【问题描述】:

我正在尝试使用 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按一次就不行了,但是按几次就可以了。

【问题讨论】:

    标签: bash


    【解决方案1】:

    使用以下代码:

    #!/bin/bash
    # type "finish" to exit
    
    stty -echoctl # hide ^C
    
    # function called by trap
    other_commands() {
        tput setaf 1
        printf "\rSIGINT caught      "
        tput sgr0
        sleep 1
        printf "\rType a command >>> "
    }
    
    trap 'other_commands' SIGINT
    
    input="$@"
    
    while true; do
        printf "\rType a command >>> "
        read input
        [[ $input == finish ]] && break
        bash -c "$input"
    done
    

    【讨论】:

    • 一个ctrl+C还是不行,我要敲三四次才能停止打印你好
    • 我不明白你,ctrl+C 就像你问的那样被困住了。它不会退出,而是在STDOUT 上打印一些字符串。
    • 我遇到了与 mar_sanbas 相同的问题,而且效果很好,感谢您的回答。在 Mac 上,运行 Bash,一个 ctrl+C 立即被捕获。
    • 重要信息,有些菜鸟可能会错过(我确实错过了):SIGINT is what you get, if you press Ctrl+C.
    【解决方案2】:

    您需要在不同的进程组中运行命令,最简单的方法是使用作业控制:

    #!/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 
    

    【讨论】:

    猜你喜欢
    • 2015-10-07
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    相关资源
    最近更新 更多