我在脚本中有以下响应检查器:
#!/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;为了获得内联的结果tee
,请在 with 之前将函数的 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