How to Run External Commands Without Leaving Vim

Bang!

Vim also allows you to execute a command directly from the editor, without needing to drop to a shell, by using bang (!) followed by the command to be run. For instance, if you’re editing a file in Vim and want to find out how many words are in the file, run

:! wc %

This tells Vim to run the file (%) through the wc utility and report the results. Vim will display the command output at the bottom of the editing window until you press Enter. Note that this command runs the file through the command, and not the contents of the buffer — so if you haven’t saved recently, it won’t report your most recent word count.

Bang works best with non-interactive commands. You wouldn’t want to run top or another interactive command using :! command , but you could drop to a shell and run such a command with :sh or Ctrl-z.

The bang command can be useful if you’re using Vim for programming. If you’re writing a PHP script, for example, you could use PHP’s syntax check option (-l) to see if your script has any syntax errors:

:! php5 -l %

If you’re working on a script or project, you might want to check it regularly, and with minimal typing. You can scroll through Vim’s command history by using the up arrow, but if you just want to rerun the last external command, you can use :!! instead.

I never remember how to do this. More good tips in the original article.

Related posts:

  1. Do a Simple Python Error Check (with pyflakes) Every Time You Save in Textmate
You should follow me on Twitter here.
Subscribe to labs via email here.

About this entry