gpt4 book ai didi

BASH - 使用陷阱 ctrl+c

转载 作者:行者123 更新时间:2023-11-29 08:42:54 25 4
gpt4 key购买 nike

我正在尝试使用读取在脚本内执行命令,当用户使用 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

关于BASH - 使用陷阱 ctrl+c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com