我有这个:
while read -r line; do echo "hello $line"; read -p "Press any key" -n 1; done < file
hello This is line 1
hello his is line 2
hello his is line 3
hello his is line 4
hello his is line 5
hello his is line 6
hello his is line 7
为什么我看不到提示“按任意键”?
答案 0 :(得分:5)
来自man bash
:
-p prompt
Display prompt on standard error, without a trailing new
line, before attempting to read any input. The prompt is
displayed only if input is coming from a terminal.
所以,因为你从文件中读取了行,但没有显示终端提示符。
答案 1 :(得分:1)
正如其他人提到的,你没有看到提示,因为当stdin是终端时,bash只打印提示。在您的情况下,stdin是一个文件。
但是这里有一个更大的错误:在我看来,你想要从两个地方读取:文件和用户。你必须做一些重定向魔术来实现这个目标:
# back up stdin
exec 3<&0
# read each line of a file. the IFS="" prevents read from
# stripping leading and trailing whitespace in the line
while IFS="" read -r line; do
# use printf instead of echo because ${line} might have
# backslashes in it which some versions of echo treat
# specially
printf '%s\n' "hello ${line}"
# prompt the user by reading from the original stdin
read -p "Press any key" -n 1 <&3
done <file
# done with the stdin backup, so close the file descriptor
exec 3<&-
请注意,上述代码不适用于/bin/sh
,因为它不符合POSIX标准。你必须使用bash。我建议通过更改提示用户的行来使其符合POSIX标准:
printf 'Press enter to continue' >&2
read <&3
答案 2 :(得分:0)
您可以明确地从控制终端/dev/tty
读取:
while IFS="" read -r line; do
echo "hello $line"
read -p "Press any key" -n 1 </dev/tty
done < file