43

I have recently discovered that if we press Ctrl+X Ctrl+E, bash opens the current command in an editor (set in $VISUAL or $EDITOR) and executes it when the editor is closed.

But it doesn't seem to be documented in the man pages. Is it documented, and if so where?

2
  • 1
    Search for edit-and-execute-command in the man page. Commented Aug 3, 2013 at 7:41
  • 10
    If you use Bash's vi mode, the short cut is Esc, V. I trigger this all the time by accident. Finally learned what it means today :) Commented Sep 23, 2014 at 14:43

2 Answers 2

52

I have found it out now. I should have read it more carefully before asking this.

The man page says:

edit-and-execute-command (C-xC-e)
          Invoke  an  editor  on the current command line, and execute the
          result as shell commands.   Bash  attempts  to  invoke  $VISUAL,
          $EDITOR, and emacs as the editor, in that order.
6
  • 19
    Be very careful with this feature. If you cancel the edit, the original command line will be immediately executed. So if you are editing rm -rf / and invoke the editor and realize you are into something dangerous and thus cancel the edit, your rootfs will be deleted without further questions asked.
    – marlar
    Commented Dec 26, 2019 at 22:44
  • 13
    @marlar if your editor is vim, you can use :cq, it makes it exit with non-zero code, and prevents the command from execution
    – karlicoss
    Commented Jan 6, 2021 at 5:39
  • 2
    @marlar ctrl-x-e without executing command immediately. Commented May 28, 2021 at 22:01
  • 1
    As an alternative (also if you remember it) just delete everything and change to ls then save & exit. Commented Nov 19, 2021 at 21:30
  • 1
    Or prefix with # Commented Jan 2, 2022 at 23:30
2

As discussed in the comments under the accepted answer, it is very convenient/safe to have an editor feature without immediate execution.

Add this to .bashrc to make Ctrl xe binding disable execution.

_edit_wo_executing() {
    local editor="${EDITOR:-nano}"
    tmpf="$(mktemp).sh"
    printf '%s\n' "$READLINE_LINE" > "$tmpf"
    $editor "$tmpf"
    READLINE_LINE="$(<"$tmpf")"
    READLINE_POINT="${#READLINE_LINE}"
    rm "$tmpf"
}

bind -x '"\C-x\C-e":_edit_wo_executing'

Credits: https://superuser.com/a/1601690/266871

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .