我有一个bash脚本,如下所示,
cat filename | while read line
do
read input;
echo $input;
done
Run Code Online (Sandbox Code Playgroud)
但这显然没有给我正确的输出,因为当我在while循环中读取它时,它试图从文件文件名读取,因为可能的I/O重定向.
还有其他方法吗?
小智 97
从控制终端设备读取:
read input </dev/tty
Run Code Online (Sandbox Code Playgroud)
更多信息:http://compgroups.net/comp.unix.shell/Fixing-stdin-inside-a-redirected-loop
Gor*_*son 53
您可以将常规stdin重定向到单元3以保持将其放入管道中:
{ cat notify-finished | while read line; do
read -u 3 input
echo "$input"
done; } 3<&0
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果你真的使用cat这种方式,用一个重定向替换它会变得更容易:
while read line; do
read -u 3 input
echo "$input"
done 3<&0 <notify-finished
Run Code Online (Sandbox Code Playgroud)
或者,您可以在该版本中交换stdin和unit 3 - 使用单元3读取文件,然后单独保留stdin:
while read line <&3; do
# read & use stdin normally inside the loop
read input
echo "$input"
done 3<notify-finished
Run Code Online (Sandbox Code Playgroud)