42

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+を1回入力すると機能しませんCが、数回入力すると機能します。

4

2 に答える 2

38

次のコードを使用します。

#!/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
于 2012-10-07T19:13:51.240 に答える
16

別のプロセス グループでコマンドを実行する必要があります。これを行う最も簡単な方法は、ジョブ コントロールを使用することです。

#!/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 
于 2012-10-08T08:24:51.023 に答える