BASH - 使用陷阱ctrl + c

mar*_*bas 28 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
Run Code Online (Sandbox Code Playgroud)

当用户使用Ctrl+时C,我希望它继续读取输入并执行其他命令.问题是当我使用如下命令时:

while (true) do echo "Hello!"; done;
Run Code Online (Sandbox Code Playgroud)

键入Ctrl+ C一次后它不起作用,但是一旦输入数次,它就会起作用.

Doc*_*tor 21

对于bash:

#!/bin/bash

trap ctrl_c INT

function ctrl_c() {
        echo "Ctrl + C happened"
}
Run Code Online (Sandbox Code Playgroud)

对于 sh:

#!/bin/sh

trap ctrl_c INT

ctrl_c () {
    echo "Ctrl + C happened"
}
Run Code Online (Sandbox Code Playgroud)


Gil*_*not 19

请尝试以下代码:

#!/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
Run Code Online (Sandbox Code Playgroud)

  • 我不明白你的意思,`ctrl+C` 就像你问的那样被困住了。它没有退出,而是在 `STDOUT` 上打印一些字符串。 (2认同)

cda*_*rke 12

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

#!/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 
Run Code Online (Sandbox Code Playgroud)