107

If I have a file with a shebang line (e.g. #!/bin/bash) open in Vim and the file has execute permissions (i.e. chmod +x) I know I can type this to execute it without leaving the editor:

:! %:p
  • : for command mode
  • ! to run a shell command
  • % to refer to the file in the current buffer
  • :p to use the full path of the current file

Is there a shorter shortcut for this frequent task?

e.g. there is a ZZ shortcut for :wq, etc.

7 Answers 7

107
:!%:p

,without the spaces, is shorter.

If you want an even shorter shortcut, you can create a custom mapping:

nnoremap <F9> :!%:p

or the more "mnemonic":

nnoremap <leader>r :!%:p
8
  • 31
    use nnoremap <F9> :!%:p<Enter> to allevate the burden of pressing Enter each time.
    – hkyi
    Commented Apr 1, 2014 at 10:41
  • 7
    use nnoremap <F9> :!%:p<Enter><Enter> to also skip Press ENTER or type command to continue after the script execution
    – user
    Commented Jul 23, 2015 at 14:41
  • 1
    nnoremap <F9> :!%:p<Enter><Enter> runs the code and returns to vim immediately. Use single Enter nnoremap <F9> :!%:p<Enter> to keep the output screen
    – askalee
    Commented Jun 8, 2018 at 3:42
  • 3
    I like having a fresh terminal for every execution so I don't get outputs from previous runs confused with the current one. To do this you can use nnoremap <F9> :!clear && %:p<Enter>
    – roganartu
    Commented Aug 3, 2019 at 15:45
  • 1
    How could I map the action of saving a file and running it to F9? If I put :w before the suggested sequence, I get E212.
    – Unknow0059
    Commented Nov 28, 2020 at 2:12
31

If you haven't set permissions you can run:

:! sh %
25

None of the previous answers work if your filename/directory path has spaces in it. Simple fix.

:!"%:p"
15

After you've executed that once, a short :!! will repeat it.

0
11

When starting vi, specify file path explicitly, like this "vi ./blablabla"

vi ./yourscript.pl

Then start with !%

The other variant is to invoke the vi command like this

!./%
6

You can add a key mapping to your .vimrc

map <F5> :!%
0

In order to execute the current file in vim if there are spaces in file name

:!./"%"

Not the answer you're looking for? Browse other questions tagged or ask your own question.