首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从文件重定向i/p时不提示读取

从文件重定向i/p时不提示读取
EN

Stack Overflow用户
提问于 2011-06-19 05:08:35
回答 3查看 222关注 0票数 3

我有这个:

代码语言:javascript
复制
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

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-06-19 05:19:33

引用自man bash

代码语言:javascript
复制
-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.

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

票数 5
EN

Stack Overflow用户

发布于 2011-06-19 06:56:04

正如其他人提到的,您看不到提示符,因为bash仅在stdin是终端时才打印提示符。在您的例子中,stdin是一个文件。

但是这里有一个更大的bug :在我看来,你想要从两个地方读取:文件和用户。你将不得不做一些重定向魔术来完成这件事:

代码语言:javascript
复制
# 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:

代码语言:javascript
复制
printf 'Press enter to continue' >&2
read <&3
票数 1
EN

Stack Overflow用户

发布于 2011-06-19 18:34:18

您可以显式地从控制终端/dev/tty读取

代码语言:javascript
复制
while IFS="" read -r line; do 
   echo "hello $line"
   read -p "Press any key" -n 1 </dev/tty
done < file
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6398908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档