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

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?


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" ]
    READLINE_LINE="some other long command"

bind -x '"  " : autocomplete'
  • Thanks for prompting me to learn a bit more about bind & readline!
    – Jeff Schaller
    Dec 23 '15 at 16:06
  • No problem. I think we both did some good learning today :) This was in an effort to answer the question unix.stackexchange.com/questions/238891/…
    – David King
    Dec 23 '15 at 16:08
  • Note: does not work for bash 3.x (RIP Mac users).
    – dlsso
    May 19 '17 at 16:38
  • What would the syntax be if you wanted to use a variable instead of " "? I tried "$char", "${char}", "$(char)" but none seem to work.
    – dlsso
    May 19 '17 at 22:39
  • Because of the outer strong (single) quotes
    – Jeff Schaller
    May 19 '17 at 23:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.