我有这个:
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为什么我看不到提示“按任意键”?
发布于 2011-06-19 05:19:33
引用自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.所以,因为您是从文件中读取行,而不是从终端提示符中读取行。
发布于 2011-06-19 06:56:04
正如其他人提到的,您看不到提示符,因为bash仅在stdin是终端时才打印提示符。在您的例子中,stdin是一个文件。
但是这里有一个更大的bug :在我看来,你想要从两个地方读取:文件和用户。你将不得不做一些重定向魔术来完成这件事:
# 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发布于 2011-06-19 18:34:18
您可以显式地从控制终端/dev/tty读取
while IFS="" read -r line; do
echo "hello $line"
read -p "Press any key" -n 1 </dev/tty
done < filehttps://stackoverflow.com/questions/6398908
复制相似问题