Welcome to End Point’s blog

Ongoing observations by End Point people

VIM Tip of the Day: running external commands in a shell

A common sequence of events when editing files is to make a change and then need to test by executing the file you edited in a shell. If you're using vim, you could suspend your session (ctrl-Z), and then run the command in your shell.

That's a lot of keystrokes, though.

So, instead, you could use vim's built-in "run a shell command"!

:!{cmd} Run a shell command, shows you the output and prompts you before returning to your current buffer.

Even sweeter, is to use the vim special character for current filename: %

Here's ':! %' is in action!

A few more helpful shortcuts related to executing things in the shell:

  • :! By itself, runs the last external command (from your shell history)
  • :!! Repeats the last command
  • :silent !{cmd} Eliminates the need to hit enter after the command is done
  • :r !{cmd} Puts the output of $cmd into the current buffer


depesz said...

you can also use "%!" to pass current buffer via some filtering command.

For example : %!nl - to number lines (different from :set nu), :%!wc to check word count on current buffer, :%!tac to reverse order of lines, and so on.

Jon Jensen said...

Yes, and you can also send line ranges rather than the whole buffer, for example, lines 4-7:

:4,7! sort -u

or line 4 through end of file:

:4,$! sort -u

And when a visual selection is active, that will automatically be the range used:

:! sort -u

Christopher Nehren said...

And in a homologous fashion, one can read the results of an external command by passing the command to run to the :r command like so:

:r !/bin/ls

Jon Jensen said...

Chris, that's the final example Selena gave in the original post, isn't it?

Christopher Nehren said...

Yes, indeed. I must have missed that part somehow. Apologies for the noise.

Selena Deckelmann said...

@depesz & Jon: Yes! Sorting is one of @gorthx's (Gabrielle Roth) favorite uses :)

Thanks for sharing!