Tip 35: Run Command in the Shell
Return to the top: <<Practical Vim>>
Executing Programs in the Shell
- invoke external programs in the shell by prefixing them with a bang symbol
References:
# If you open the file in vim, # then you can \"ayy@a the next line to execute the vim command: :h :!
-
Comparison
-
:!ls: call thelscommand in the shell -
:ls: call Vim's built-in command, which shows the contents of the buffer list
-
-
%: shorthand for the current file name
References:
# If you open the file in vim, # then you can \"ayy@a the next line to execute the vim command: :h cmdline-special
- filename modifiers
References:
# If you open the file in vim, # then you can \"ayy@a the next line to execute the vim command: :h filename-modifiers
-
:shell: start an iterative shell session
References:
# If you open the file in vim, # then you can \"ayy@a the next line to execute the vim command: :h :shell
-
Alternative of
:shelland:exit:<C-z>and<fg>
Using the Contents of a Buffer for Standard Input or Output
-
:read !{cmd}: put the output from the{cmd}into the current buffer
References:
# If you open the file in vim, # then you can \"ayy@a the next line to execute the vim command: :h read!
-
:write !{cmd}: use the contents of the buffer as standard input for the specified{cmd}
References:
# If you open the file in vim, # then you can \"ayy@a the next line to execute the vim command: :h :write_c
-
Comparison
-
:write !sh: pass the contents of the buffer as standard input to the externalshcommand -
:write ! sh: pass the contents of the buffer as standard input to the externalshcommand -
:write! sh: write the contents of the buffer to a file called "sh" by calling the:write!command
-
-
Effect of
:write !sh: each line of the current buffer is executed in the shell
Example:
:h :rename-files
Filtering the Contents of a Buffer Through an External Command
References:
# If you open the file in vim, # then you can \"ayy@a the next line to execute the vim command: :h :range!
-
shortcut for setting the range of a
:[range]!{filter}command:!{motion}
References:
# If you open the file in vim, # then you can \"ayy@a the next line to execute the vim command: :h !
e.g. invoke !G → vim opens a prompt with the :.,$! range set up for us
| Command | Effect |
:shell
|
Start a shell (return to vim by typing exit)
|
:!{cmd}
|
Execute {cmd} with the shell
|
:read !{cmd}
|
Execute {cmd} in the shell and insert its standard input below the cursor
|
:[range]write !{cmd}
|
Execute {cmd} in the shell with [range] lines as standard input
|
[range]!{filter}
|
Filter the specified [range] through external program {filter}
|