在bash脚本中,如何将键绑定到函数?

bfo*_*ine 3 bash key-bindings

我做了以下事情:

#! /bin/bash
a=2

function up_a() {
    a=$((a+1));
}

while (true);
do
    echo "a=$a";
    up_a;
    sleep 1;
done
Run Code Online (Sandbox Code Playgroud)

它工作正常:

$ ./test.sh
a=2
a=3
...
Run Code Online (Sandbox Code Playgroud)

现在,我尝试以下方法:

#! /bin/bash
a=2

function up_a() {
    a=$((a+1));
}

bind -x '"p": up_a';

while (true);
do
    echo "a=$a";
    sleep 1;
done
Run Code Online (Sandbox Code Playgroud)

当我测试它时:

$ . test.sh
Run Code Online (Sandbox Code Playgroud)

(我需要"导入"脚本以使用bind命令,带source.)

a=2
a=2
...
Run Code Online (Sandbox Code Playgroud)

(我按了几次"p"键)

怎么了 ?

gra*_*ity 6

使用的键绑定bind仅影响交互式文本输入(readline库).当运行程序(甚至是内置程序while)时,终端切换到标准的"熟"模式,并输入当前正在运行的程序(在这种情况下,sleep将接收输入).

您可以手动读取密钥:

read -N 1 input

echo "Read '$input'"
Run Code Online (Sandbox Code Playgroud)

但是,如果要同时运行while循环读取输入,则必须在单独的进程中执行此操作(bash不支持线程).由于变量是进程的本地变量,因此最终结果必须相当复杂.