bash readline: Key binding that executes an external command

Not all bash line editing is controlled from ~/.inputrc; much of it is configured via the bind builtin. In this case, you want something like

bind -x '"\C-gu":uptime'

in your ~/.bashrc.


The other answer provides a solution, that executes the command in a new line. This is useful in some cases, but most of the time my workflow is such, that either I want to

  • Insert the result of an inline execute command in my current command-line (example below)
  • Execute the command truly in the background, no output, no changes in current command line

I use these two principles much more often than the variant @geekosaur showed. Here is an example:

bind '"\C-gd":"\C-u`date +%Y%m%d%H%M`\e\C-e\C-a\C-y\C-e"'

This bind CTRL-gd to kill the existing command (saving it in the cut buffer), insert some shell command, in this case date +%Y%m%d%H%M for a nice timestamp, execute that in-place, and then paste the saved command back to the front of the command-line.

I have a bunch of commands, that output some information from my system, that I regularly use in other command lines, think get_lan_ip, get_gw_ip, get_gw_pubip, get_ns_ip, get_root_block_dev, get_email_addr, get_phone_number and so on. Basically like programmable abbreviations! and all of them one key-stroke behind \C-g away only.

The other very useful use-case for me is calling functions inline, that do not produce output, but silently trigger a background action, like mediaplayer_next, mediaplayer_pause, speakerphone_answer, ... for when I want to trigger things without leaving my terminal, and without losing sight of my current windows contents for even a moment ;)