在循环中读取用户输入

我有一个 bash 脚本,类似于,

cat filename | while read line
do
read input;
echo $input;
done

但是这显然没有给出正确的输出,因为当我在 while 循环中读取时,由于可能的 I/O 重定向,它试图从文件名中读取。

还有别的办法吗?

130256 次浏览

试着像这样改变循环:

for line in $(cat filename); do
read input
echo $input;
done

Unit test:

for line in $(cat /etc/passwd); do
read input
echo $input;
echo "[$line]"
done

看起来您读取了两次,不需要在 while 循环中读取。另外,您不需要调用 cat 命令:

while read input
do
echo $input
done < filename

从控制终端设备读取:

read input </dev/tty

更多信息: http://compgroups.net/comp.unix.shell/Fixing-stdin-inside-a-redirected-loop

You can redirect the regular stdin through unit 3 to keep the get it inside the pipeline:

{ cat notify-finished | while read line; do
read -u 3 input
echo "$input"
done; } 3<&0

顺便说一句,如果你真的这样使用 cat,用重定向代替它,事情就变得更简单了:

while read line; do
read -u 3 input
echo "$input"
done 3<&0 <notify-finished

或者,你可以在那个版本中交换 stdin 和3单元——读取带有3单元的文件,不要管 stdin:

while read line <&3; do
# read & use stdin normally inside the loop
read input
echo "$input"
done 3<notify-finished
echo "Enter the Programs you want to run:"
> ${PROGRAM_LIST}
while read PROGRAM_ENTRY
do
if [ ! -s ${PROGRAM_ENTRY} ]
then
echo ${PROGRAM_ENTRY} >> ${PROGRAM_LIST}
else
break
fi
done

我在 read 中找到了这个参数 u。

“-u 1”表示“从 stdout 读取”

while read -r newline; do
((i++))
read -u 1 -p "Doing $i""th file, called $newline. Write your answer and press Enter!"
echo "Processing $newline with $REPLY" # united input from two different read commands.
done <<< $(ls)