当我从文件redirect时读取不提示

我有这个:

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 

为什么我看不到提示“按任意键”?

引用从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. 

所以,因为你从文件中读取行,而不是从终端提示符不显示。

正如其他人提到的,你看不到提示,因为bdin只在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 

您可以明确从控制终端/dev/tty读取:

 while IFS="" read -r line; do echo "hello $line" read -p "Press any key" -n 1 </dev/tty done < file