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

标签 bash key-bindings

我做了以下事情:

#! /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/

相关文章:

javascript - JavaScript 中鼠标点击模拟键盘按键

mysql - 使用 bash 从 MySQL 到 PostgreSQL 的 Oneliner 管道

bash - 在 yad 笔记本中添加按钮

bash - git log 的输出在通过管道传输到文件时丢失了——我错过了什么?

python - 如何在 python tkinter 中绑定(bind) Ctrl+/?

Java游戏: How to overcome a hardware-limitation of a keyboard

emacs 键绑定(bind)在终端中不起作用

bash - 在 bash 中导出环境变量时何时使用括号?

linux - shell 脚本 : read the output to run the next command

python - Python (Linux) 中的多媒体键