我做了以下事情:
#! /bin/bash
a=2
function up_a() {
a=$((a+1));
}
while (true);
do
echo "a=$a";
up_a;
sleep 1;
done
它工作正常:
$ ./test.sh
a=2
a=3
...
现在,我尝试以下操作:
#! /bin/bash
a=2
function up_a() {
a=$((a+1));
}
bind -x '"p": up_a';
while (true);
do
echo "a=$a";
sleep 1;
done
当我测试它时:
$ . test.sh
(我需要“导入”脚本以使用 bind
命令,使用 source
或 。
)
a=2
a=2
...
(我按了几次“p”键)
怎么了?
最佳答案
使用 bind
的键绑定(bind)只影响交互式文本输入(readline 库)。当运行一个程序时(即使是内置的while
),终端会切换到标准的“cooked”模式,并将输入提供给当前正在运行的程序(在这种情况下,sleep
将接收输入)。
您可以手动读取 key :
read -N 1 input
echo "Read '$input'"
但是,如果您想同时运行 while
循环 和 读取输入,则必须在不同的进程中执行(bash 不支持线程).由于变量是流程的局部变量,因此最终结果必须相当复杂。
关于bash - 在 bash 脚本中,如何将键绑定(bind)到函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8831458/