In ZSH, how can I use bindkey
to bind a key sequence to a script?

- 4,236
- 3
- 21
- 35

- 409
- 5
- 8
3 Answers
You can define a widget that calls your script:
my-script_widget() my-script its args
zle -N my-script_widget
bindkey '\ej' my-script_widget
But why would you want to call your script directly from the zle?
If it displays anything, it will mess up the display. If you want its output displayed as other widget messages, you can do:
my-script_widget() zle -M "$(my-script its args)"
Or if you want the output inserted at the cursor:
my-script_widget() LBUFFER+=$(my-script its args)

- 544,893
To expand a bit on @suside's answer:
Since bindkey -s
just sends key sequences, if theres already something on your prompt and you try and use the binding, it just types it in after whats already at the prompt. This can be fixed by sending kill-whole-line
to clear the prompt before typing your command/script in.
kill-whole-line
is typically bound to ^u
(Ctrl+U
), see docs. If its not, you can bind it with:
bindkey '^u' kill-whole-line
Then, you can do:
bindkey -s '\eb' '^u/path/to/script.sh^M'
which binds Alt+b
to kill the current line before typing your characters, then sending ^M
(newline).
Alt-B
to the script, that causes/path/to/script.sh\n
to be inserted as if typed. For instance if you typeAlt-B
after having enteredecho
, that will just run theecho /path/to/script.sh
command and get you back to an empty prompt (with theecho
you had entered earlier gone). – Stéphane Chazelas Aug 13 '16 at 07:21bindkey -s '\eb' '/path/to/script.sh^M'
– mihai Jun 03 '17 at 22:38