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

标签 linux bash

有没有办法在脚本运行时更改脚本的输出? 假设我有一个名为“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/

相关文章:

django - 从 shell 脚本调用 Django 命令不同于手动调用

linux - 移动不同文件夹中的文件更改名称

linux - 我想在匹配后使用 shell 脚本中的 sed 命令在文件中添加 java 选项行

Python:如何在子进程中使用反引号?

Python 标准输出日志记录 : terminal vs bash file

c++ - snprintf "date"和文件位置问题

php - 在 Linux 中从文件句柄确定文件路径

php - 名称 image.php.jpg 中带有 .php 的文件名问题

Bash 将存储的 "boolean"值与什么进行比较?

node.js - 无法使用 Git Bash 运行 mongo/mongod,但它在 Git CMD 中运行(mongo : not found)