Aditya
Aditya

Reputation: 364

A shortcut to fire up vim on the text typed on the command line

I typed a very long command on the command line – only to discover that Bash doesn't like embedded single quotes. It is a bare tty and my only way to save this command for running from within a file is to open vim and start typing this very long command again...

Isn't there a shortcut to fire up vim on the text typed on the command line – directly from the command line?

Upvotes: 1

Views: 418

Answers (2)

mattb
mattb

Reputation: 3063

I found the answer for my case here:

First off a warning from @marlar (I made myself a function to protect myself from this, see below):

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 <forward slash> and invoke the editor and realize you are into something dangerous and thus cancel the edit, your root file system will be deleted without further questions asked.

From the OP @Kartik:

The bash 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.

And from @Mark E. Haase

If you use Bash's vi mode, the short cut is Esc, V...

I actually also find that doing just v is sufficient to launch vim with the bash command sitting there.

From @karlicoss:

if your editor is vim, you can use :cq, it makes it exit with non-zero code, and prevents the command from execution

Because I'm paranoid about the rm -rf command (I once deleted 2Tb of brain data with that - 10 days into switching to linux... lucky the sysadmin had a backup... actual quote: "I've never seen anything that stupid in my 20 years doing this job"... but I digress) I put the following in my vimrc to immediately comment out the command if I accidentally bring up vim and reflexively exit:

function! CheckBashEdit()
    " if the file matches this highly specific reg exp, comment the line
    "(e.g. a file that looks like: /tmp/bash-fc.xxxxxx)
    if match(@%, "\/tmp\/bash-fc\.......") != -1
        " comment out the command
        silent! execute ":%normal! I# "
        write
    endif
endfunction

" if we ended up in vim by pressing <ESC-v>, put a # at the beggining of
" the line to prevent accidental execution (since bash will execute no
" matter what! Imagine rm -rf <forward slash> was there...)
autocmd BufReadPost * :call CheckBashEdit()

Upvotes: 1

romainl
romainl

Reputation: 196751

Sure there is. The following command will edit the current command-line in $VISUAL:

C-x C-e

Upvotes: 3

Related Questions