Search code examples
bashkey-bindings

In a bash script, how can I bind a key to a function?


I did the following:

#! /bin/bash
a=2

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

while (true);
do
    echo "a=$a";
    up_a;
    sleep 1;
done

It's working fine:

$ ./test.sh
a=2
a=3
...

Now, I try the following:

#! /bin/bash
a=2

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

bind -x '"p": up_a';

while (true);
do
    echo "a=$a";
    sleep 1;
done

When I test it:

$ . test.sh

(I need to "import" the script to use bind command, with source or .)

a=2
a=2
...

(I pressed the "p" key several times)

What's wrong ?


Solution

  • Key bindings using bind only affect the interactive text input (the readline library). When running a program (even a built-in while) the terminal is switched to standard "cooked" mode and input is given to the currently running program (in this case, sleep would receive the input).

    You can read the keys manually:

    read -N 1 input
    
    echo "Read '$input'"
    

    However, if you want to run the while loop and read input at the same time, you will have to do it in separate processes (bash does not support threads). Since variables are local to a process, the end result will have to be fairly complicated.