102

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.

Robottinosino
  • 10,384
  • 17
  • 59
  • 97

7 Answers7

100
:!%: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
romainl
  • 186,200
  • 21
  • 280
  • 313
  • 29
    use nnoremap :!%:p to allevate the burden of pressing Enter each time. – hkyi Apr 01 '14 at 10:41
  • 6
    use `nnoremap :!%:p` to also skip `Press ENTER or type command to continue` after the script execution – user Jul 23 '15 at 14:41
  • 1
    `nnoremap :!%:p` runs the code and returns to vim immediately. Use single Enter `nnoremap :!%:p` to keep the output screen – askalee Jun 08 '18 at 03:42
  • [About `nnoremap`](https://stackoverflow.com/a/18917038). Also note that this won't handle file names with spaces properly, see [this answer](https://stackoverflow.com/a/46348040/5267751) below. – user202729 Jun 27 '18 at 09:22
  • 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 :!clear && %:p` – roganartu Aug 03 '19 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 Nov 28 '20 at 02:12
  • If you dont use the `p` you may get the error "shell returned 127" – alchemy Apr 03 '22 at 23:04
  • fyi, default leader is \ ..use `:echo mapleader` (undefined error if default) or `:let mapleader = ","` (example) – alchemy Oct 10 '22 at 20:44
31

If you haven't set permissions you can run:

:! sh %
James Dunmore
  • 1,310
  • 11
  • 16
24

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

:!"%:p"
nullUser
  • 1,601
  • 1
  • 12
  • 29
13

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

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
10

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

!./%
armagedescu
  • 1,758
  • 2
  • 20
  • 31
5

You can add a key mapping to your .vimrc

map <F5> :!%
jpmuc
  • 1,092
  • 14
  • 30
0

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

:!./"%"
Udesh
  • 2,415
  • 2
  • 22
  • 32