Tip: expand a bash commandline as you type it

UNIX: another useful tip. Bash supports a wide variety of command line editing tricks; you have the usual GUIish editing (backspace, insert new characters, delete, blah blah) through the GNU Readline library, and in addition to that you have the traditional csh-style history expansion (like ‘!!’ to refer to the previous command typed).

The latter are great, but they won’t actually be expanded until you hit Enter and run the command line. That can be inconvenient, resulting in the user being forced to reach for the rodent for some cut’n'paste instead.

Here’s a handy trick — add this line to ~/.inputrc (creating the file if necessary):

Control-x: shell-expand-line

Start a new bash shell. Now, if you type CTRL-X during command line entry, any shell metacharacters will be expanded on the current command line. For example:

% echo Hello world
Hello world

% echo Hi !$       (press CTRL-X)
           (current command line expands to:)
% echo Hi world

There’s a few more commands supported, but none of them are really quite as useful as shell-expand-line.

Update: ‘Smylers’ wrote to point me at this UKUUG talk from 2003 which discusses .inputrc expansions, and provides some insanely useful tips.

In particular, Magic Space clearly knocks this tip into a cocked hat, by performing the expansion on the fly as you type the command, with no additional keypresses — amazing! Bonus: it works if you use Emacs-mode line editing as well as Vi-mode.

I strongly recommend reading that paper — lots of other good tips there.

This entry was posted in Uncategorized and tagged , , , , , , , , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

2 Comments

  1. Posted May 16, 2006 at 11:59 | Permalink

    After several months of use, I should point out that Magic Space does have its problems btw. Here’s an example of a common case where it screws up:

      % echo hello world
      % echo hi !$
    

    Do not press Enter; instead, press cursor-left twice, so the cursor is on the “!” character, then press Space. The result is:

      % echo hi wor ld
    

    Still, I’m liking it ;)

  2. jeff
    Posted September 30, 2009 at 20:12 | Permalink

    This should work:

    echo hello world

    echo hi !-1:1-2 [magic space]