开发者

read not prompting when i/p redirected from a file

I have this:

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 h开发者_开发百科is is line 4
hello his is line 5
hello his is line 6
hello his is line 7

Why do I not see the prompt "Press any key" ?


Quote from 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.

So, because you read lines from file but not from terminal prompt not displayed.


As others mentioned, you don't see the prompt because bash only prints the prompt when stdin is a terminal. In your case, stdin is a file.

But there's a bigger bug here: It seems to me that you want to read from two places: a file and the user. You'll have to do some redirection magic to accomplish this:

# 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<&-

Note that the above code won't work with /bin/sh because it's not POSIX compliant. You'll have to use bash. I'd recommend making it POSIX compliant by changing the line that prompts the user:

printf 'Press enter to continue' >&2
read <&3


You may explicitly read from the controlling terminal /dev/tty:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜