vimtricks.wiki Concise Vim tricks, one at a time.

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 shell
  • command is 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 !command to insert the output of a shell command directly into the buffer (e.g., :r !date inserts the current date)
  • Use :! followed by the up arrow to recall previous shell commands
  • Use :silent !command to run a command without showing the output
  • Use :.!command to replace the current line with the output of a command — this is called filtering
  • Use :%!sort to sort the entire file by piping it through the external sort command
  • In visual mode, select lines and type :!command to 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 :term to open a full interactive terminal inside Vim instead of running a single command

Next

How do I edit multiple lines at once using multiple cursors in Vim?