BASH - 使用陷阱ctrl + c

时间:2012-10-07 19:07:22

标签: 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 时,我希望它继续读取输入并执行其他命令。问题是,当我使用如下命令时:

while (true) do echo "Hello!"; done;

在我键入 Ctrl + C 一次后它无法正常工作,但只要我输入几次就可以正常工作。

2 个答案:

答案 0 :(得分:12)

请尝试以下代码:

#!/bin/bash
# type "finish" to exit

# function called by trap
other_commands() {
    printf "\rSIGINT caught      "
    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

答案 1 :(得分:10)

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

#!/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 
相关问题