How to run Unix Commands in vi/vim editor

There are some scenarios where unix admin wants to run unix commands and insert the output of unix command in vi editor without leaving it. This can be possible using below steps :

:!UNIX_command

Example : Run the ifconfig command within the /etc/hosts file.

linuxtechi@mail:~$ sudo vi /etc/hosts

ifconfig-command-in-editor

Insert UNIX Command Ouptut in vi editor :

To insert the output of a UNIX command into a file, immediately after the cursor use below syntax in vi editor

:r!command

Example: Insert the output of hostname in /etc/hosts file.

linuxtechi@mail:~$ sudo vi /etc/hosts

insert-unix-command-output

When we press enter , the output of hostname command will be inserted in the file just after the cursor posotion.

Starting Shell in vi Editor

We can start the unix shell within the editor , to start a shell use below command :

:<Shell>

Type of a shell that is started is determined by the $SHELL variable. And to return back to editor use exit or Ctrl-D

Example : Start sh shell in vi editor :

linuxtechi@mail:~$ sudo vi /etc/hosts

shell-in-vi-editor

Note: Above discussed features becomes very useful if you are using vi/vim to document a UNIX command and you wanted to include examples of the output from this command.

1 Response

  1. Shawn H Corey says:

    You can filter lines through a shell command. For example, to sort some lines:

    Go the the top of the lines and press: ma

    Go to the bottom of the lines and press: !’asort
    and then RETURN.

    The lines will be sorted. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *