Shell 在while read循环中读取密钥失败
这是我的脚本,用于检测按下的键:Shell 在while read循环中读取密钥失败,shell,stdin,io-redirection,Shell,Stdin,Io Redirection,这是我的脚本,用于检测按下的键: #!/bin/bash echo "Reading keys." while [ "x$keypress" = "x" ]; do read -n 1 -t 1 -s keypress printf "." done printf "\n" echo "Pressed key: "$keypress 这似乎工作正常(例如,过一会儿按“q”键): 但是,如果我将其放入一个循环中,该循环读取我的File.txt,并等待每一行的键: #!/bin/bash
#!/bin/bash
echo "Reading keys."
while [ "x$keypress" = "x" ]; do
read -n 1 -t 1 -s keypress
printf "."
done
printf "\n"
echo "Pressed key: "$keypress
这似乎工作正常(例如,过一会儿按“q”键):
但是,如果我将其放入一个循环中,该循环读取我的File.txt
,并等待每一行的键:
#!/bin/bash
MyList=File.txt
while IFS=, read -ra ListLine
do
echo "Processing line: "$ListLine
echo "Press [S] to count as Secret or [P] to count as Public."
while [ "x$keypress" = "x" ]; do
read -n 1 -t 1 -s keypress
printf "."
done
printf "\n"
echo "Pressed key: "$keypress
done < "$MyList"
这是文件.txt
内容:
d:\Temp
c:\Temp
e:\Temp
我在某个地方读到,问题来自
,它在第一次循环后工作,因为keypress是空的,但在随后的调用中,keypress仍然设置为在第一次循环中设置的值。
您只需将keypress变量设置为空字符串。您可以从不同的文件描述符读取,并重构内部循环
while IFS=, read -r -u 3 -a ListLine
do
echo 'Processing line:' "$ListLine"
echo 'Press [S] to count as Secret or [P] to count as Public.'
until read -n 1 -t 1 -s keypress
do
printf .
done
echo
echo 'Pressed key:' $keypress
done 3< File.txt
当IFS=,读取-r-u3-a列表行
做
回显“处理行:”“$ListLine”
echo'按[S]算作机密,或按[P]算作公共。'
直到读到-n1-t1-s键为止
做
printf。
完成
回声
echo“按下键:”$keypress
完成3
Mmm。。我正在测试,你似乎是对的,克劳迪奥。谢谢你。您应该编辑您的答案,以增强它,以符合论坛规则。至少,我认为您必须添加一个示例(只需对我的脚本进行简单的修改就足够了)。谢谢。你的脚本似乎有一些小的修改,但我认为它是正确的。请注意,whileifs=,read-r-u3-a ListLine
和whileifs=,read-ra ListLine
d:\Temp
c:\Temp
e:\Temp
#!/bin/bash
MyList=File.txt
while IFS=, read -ra ListLine <&3
do
echo "Processing line: "$ListLine
echo "Press [S] to count as Secret or [P] to count as Public."
while [ "x$keypress" = "x" ]; do
read -n 1 -t 1 -s keypress
printf "."
done
printf "\n"
echo "Pressed key: "$keypress
done 3< "$MyList"
$ ./prueba07.sh
Processing line: d:\Temp
Press [S] to count as Secret or [P] to count as Public.
..
Pressed key: p
Processing line: c:\Temp
Press [S] to count as Secret or [P] to count as Public.
Pressed key: p
Processing line: e:\Temp
Press [S] to count as Secret or [P] to count as Public.
Pressed key: p
Processing line:
Press [S] to count as Secret or [P] to count as Public.
Pressed key: p
read -n 1 -t 1 -s keypress </dev/tty
#!/bin/bash
MyList=File.txt
while IFS=, read -ra ListLine <&3
do
echo "Processing line: "$ListLine
echo "Press [S] to count as Secret or [P] to count as Public."
while [ "x$keypress" = "x" ]; do
read -n 1 -t 1 -s keypress
printf "."
done
printf "\n"
echo "Pressed key: "$keypress
unset keypress
done 3< "$MyList"
while IFS=, read -r -u 3 -a ListLine
do
echo 'Processing line:' "$ListLine"
echo 'Press [S] to count as Secret or [P] to count as Public.'
until read -n 1 -t 1 -s keypress
do
printf .
done
echo
echo 'Pressed key:' $keypress
done 3< File.txt