If you’re a command line junkie like me, your commands sometimes tend to get long and complicated.

And then you spot a typo somewhere in the middle.

Or you forgot a command somewhere.

You now have two options: You can use the arrow keys (or, if you know your shell, the Emacs/Vi movements) to navigate there, and fix it.

Or you could just use your editor.

Zsh

If you’re using zsh (as you should), you could add the following to your .zshrc:

# Enable Ctrl-x-e to edit command line
autoload -U edit-command-line
# Emacs style
zle -N edit-command-line
bindkey '^xe' edit-command-line
bindkey '^x^e' edit-command-line
# Vi style:
# zle -N edit-command-line
# bindkey -M vicmd v edit-command-line

Then, reload your .zshrc.

Now all you need to do is hit Ctrl-x Ctrl-e (Ctrl-x e also works) or, if you use vi style, ESC v, and zsh will launch $VISUAL or $EDITOR, allowing you to edit the current command to your hearts content, and once you save & close your editor’s window, ZSH will execute your command.

Bash

Readline (which is what Bash uses) has a similar command called edit-and-execute-command, and by default it’s already bound to Ctrl-x Ctrl-e, so no config necessary.

More?

You can find this and other useful stuff in my dotfiles.

Update 2.5.2010: @citizen428 brought the builtin fc (fix command) to my attention. fc allows you to edit commands in your history, and reruns them when you’re finished.