gpt4 book ai didi

linux - 在 Bash 中运行时按下按键时更改脚本输出

转载 作者:太空宇宙 更新时间:2023-11-04 09:33:20 26 4
gpt4 key购买 nike

有没有办法在脚本运行时更改脚本的输出?假设我有一个名为“numbers”的脚本并且它正在运行。该脚本使用此循环打印从 1 到 49 的数字:

for ((a=1; a<50; a++))
do
echo $a
sleep 1
done

如何在循环运行时改变它的输出?比方说,如果我在运行过程中按 a 或 b,它应该从结果中减去 1。

最佳答案

如评论中所述,在如此短的运行期间没有时间做任何事情。但是,如果我让运行时间更长更慢,我可以证明类似于您所要求的内容。

declare -i a b c # Ensure these values are treated as integers
b=1
for ((a=0; a < 10**6; a+=b)); do
read -s -N1 -t.3 c && b=c
printf '%d...' "$a"
done
echo

read 参数分解:

read -s   # Don't echo output
-N1 # Read one character of input*
-t.3 # Wait for .3 seconds before giving up
c &&
b=c # If read was successful, assign value to c, then b

这里有些疯狂。享受:

declare -i a b
b=1
for ((a=0; a < 10**6; a+=b)); do
if read -s -N1 -t.01 c; then
case $c in
j) b=b+1;;
k) b=b-1;;
esac
fi
printf '%d...' "$a"
done
echo

*我注意到 bash v3 似乎使用 read -n1 和 v4 read -N1

关于linux - 在 Bash 中运行时按下按键时更改脚本输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29223496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com