Bash Readline – Using Bind to Read the Current Command Line

bashreadline

I'm using bind -x to execute a script whenever a certain key sequence is pressed.

For example I have a script at /usr/local/bin/foo with the contents

#!/bin/bash
echo foo

If I run bind -x '" ": /usr/local/bin/foo' then every time I press the space bar twice it echos "foo". So far so good.

What I want to be able to do is access (and ideally modify) the current command that's being entered. If I type some really long command (there are two spaces at the end) my script gets executed but how can it see that I've already entered some really long command and change it to some other long command?

Best Answer

Based on this answer, I think you would have to make your script into a sourced bash function, have it modify READLINE_LINE (and READLINE_POINT according to the new length / desired cursor point), and then bind -x '" " : that-function-name'.

Just to clarify; if you only want to modify some commands with double-space, do something like:

autocomplete() {
if [ "$READLINE_LINE" = "some really long command" ]
then
    READLINE_LINE="some other long command"
    READLINE_POINT=23
fi
}

bind -x '"  " : autocomplete'
Related Question