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 ?
Key bindings using
bindonly affect the interactive text input (the readline library). When running a program (even a built-inwhile) the terminal is switched to standard “cooked” mode and input is given to the currently running program (in this case,sleepwould receive the input).You can read the keys manually:
However, if you want to run the
whileloop 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.