How do I run a shell command from inside Vim?
Answer
:!command
Explanation
The :!command syntax lets you execute any shell command directly from within Vim without leaving the editor. Vim suspends its display, runs the command in your shell, shows the output, and then returns you to Vim when you press Enter.
How it works
:enters command-line mode!tells Vim to pass the rest of the line to your shellcommandis any valid shell command (e.g.,ls,git status,make,python script.py)
Example
To list the files in the current directory:
:!ls -la
Vim shows the output of ls -la in the terminal. Press Enter to return to your buffer.
To compile the current file:
:!gcc % -o output
The % is expanded to the current file name, so this compiles the file you are editing.
Special expansions
%— the current file name%:p— the full path of the current file%:h— the directory of the current file%:r— the current file name without its extension#— the alternate (previous) file name
Tips
- Use
:r !commandto insert the output of a shell command directly into the buffer (e.g.,:r !dateinserts the current date) - Use
:!followed by the up arrow to recall previous shell commands - Use
:silent !commandto run a command without showing the output - Use
:.!commandto replace the current line with the output of a command — this is called filtering - Use
:%!sortto sort the entire file by piping it through the externalsortcommand - In visual mode, select lines and type
:!commandto filter the selection through the command — the selected text becomes the command's stdin, and the output replaces the selection - Use
:terminal(Vim 8+) or:termto open a full interactive terminal inside Vim instead of running a single command