Vim: execute current file?

Vim

Vim Problem Overview


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.

Vim Solutions


Solution 1 - Vim

:!%: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

Solution 2 - Vim

If you haven't set permissions you can run:

:! sh %

Solution 3 - Vim

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

:!"%:p"

Solution 4 - Vim

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

Solution 5 - Vim

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

!./%

Solution 6 - Vim

You can add a key mapping to your .vimrc

map <F5> :!%

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobottinosinoView Question on Stackoverflow
Solution 1 - VimromainlView Answer on Stackoverflow
Solution 2 - VimJames DunmoreView Answer on Stackoverflow
Solution 3 - VimnullUserView Answer on Stackoverflow
Solution 4 - VimIngo KarkatView Answer on Stackoverflow
Solution 5 - VimarmagedescuView Answer on Stackoverflow
Solution 6 - VimjpmucView Answer on Stackoverflow