BASH-使用陷阱ctrl + c [英] BASH - using trap ctrl+c

查看:101
本文介绍了BASH-使用陷阱ctrl + c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用read在脚本内执行命令,并且当用户使用 Ctrl + C 时,我想停止执行命令,但是不退出脚本. 像这样:

I'm trying to execute commands inside a script using read, and when the user uses Ctrl+C, I want to stop the execution of the command, but not exit the script. Something like this:

#!/bin/bash

input=$1
while [ "$input" != finish ]
do
    read -t 10 input
    trap 'continue' 2
    bash -c "$input"
done
unset input

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

When the user uses Ctrl+C, I want it to continue reading the input and executing other commands. The problem is that when I use a command like:

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

在我键入 Ctrl + C 一次后,它不起作用,但是当我多次键入时,它就起作用了.

It doesn't work after I type Ctrl+C one time, but it works once I type it several times.

推荐答案

使用以下代码:

#!/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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆