Art*_*yan 7 bash shell-script read
我有一个下面的小 bash 脚本
var=a
while true :
do
echo $var
sleep 0.5
read -n 1 -s var
done
Run Code Online (Sandbox Code Playgroud)
它只是打印用户输入的字符并等待下一次输入。我想要做的实际上不是阻止读取,即每 0.5 秒打印一次用户输入的最后一个字符。当用户按下某个键时,它应该无限地继续打印新键,直到下一次按下按键,依此类推。
有什么建议?
mur*_*uru 16
来自help read:
-t timeout time out and return failure if a complete line of input is
not read within TIMEOUT seconds. The value of the TMOUT
variable is the default timeout. TIMEOUT may be a
fractional number. If TIMEOUT is 0, read returns immediately,
without trying to read any data, returning success only if
input is available on the specified file descriptor. The
exit status is greater than 128 if the timeout is exceeded
Run Code Online (Sandbox Code Playgroud)
所以尝试:
while true
do
echo "$var"
IFS= read -r -t 0.5 -n 1 -s holder && var="$holder"
done
Run Code Online (Sandbox Code Playgroud)
使用该holder变量是因为变量在使用时会丢失其内容,read除非它是只读的(在这种情况下它无论如何都没有用),即使read超时:
$ declare -r a
$ read -t 0.5 a
bash: a: readonly variable
code 1
Run Code Online (Sandbox Code Playgroud)
我找不到任何方法来防止这种情况。