スクリプトの応答チェッカー

スクリプトの応答チェッカー

私のスクリプトには、次の応答チェッカーがあります。

#!/bin/bash

test_fn()
{
WARNFILE=$1
echo
echo "--- BEGIN ---"
cat ${WARNFILE}
echo "--- END ---"
echo

while true; do
    read -r -n 1 -p "Continue? [y/n]: " REPLY
    case $REPLY in
      [yY]) break ;;
      [nNqQ]) echo;exit ;;
      *) printf "\033[31m%s\033[0m\n" " invalid input: ${REPLY}"
    esac
done
}

test_fn /tmp/warning 

良い結果...

$ ./test.sh

--- BEGIN ---
test warning
--- END ---

Continue? [y/n]: a invalid input: a
Continue? [y/n]: s invalid input: s
Continue? [y/n]: d invalid input: d
Continue? [y/n]: w invalid input: w
Continue? [y/n]: s invalid input: s
Continue? [y/n]: q
$

...壊れるまで:

test_fn /tmp/warning

ラインを含む:

test_fn /tmp/warning | tee -a /tmp/logfile

その後、行を混ぜます。

$ ./test.sh

--- BEGIN ---
test warning
Continue? [y/n]: --- END ---

aContinue? [y/n]:  invalid input: a
sContinue? [y/n]:  invalid input: s
dContinue? [y/n]:  invalid input: d
fContinue? [y/n]:  invalid input: f
q
$

なぜそれがうまく機能するのか誰が知っていますか?

ベストアンサー1

コメントを回答に変換するには:

read -p結果をインラインで取得するには、stderrにプロンプ​​トを作成し、withのtee前に関数のstderrをstdoutにパイプしますtee

test_fn /tmp/warning 2>&1 | tee -a /tmp/logfile

実績のあるread動作:

$ read -p "my prompt: " >/dev/null
my prompt: hi
$ read -p "my prompt: " 2>/dev/null
hi

おすすめ記事