Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
BASH-使用trap ctrl+;C_Bash - Fatal编程技术网

BASH-使用trap ctrl+;C

BASH-使用trap ctrl+;C,bash,Bash,我试图使用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时,我希望它继续读取输入并执行其他命令。问题是,当

我试图使用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
# 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

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

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

对于一个ctrl+C仍然不起作用,我必须键入3到4次才能停止打印HelloI我不明白,
ctrl+C
就像你要求的那样被困住了。它没有退出,而是在STDOUT上打印了一些字符串。我遇到了与mar_sanbas相同的问题,效果很好,谢谢你的回答。在Mac上,运行Bash时,一个ctrl+C立即被捕获。