syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

You are here: Linux101 > Shell 101 > shell101_vi

Linux Shell 101

Question:
In Linux101 how to use vi editor?
Tags: linux shell bash vi

All editors want me to do one of two actions:
  • Issue commands
  • Type in text
In GUI editors I can usually issue commands via a menu at the top.

In vi I can issue a command after I press the esc-key.

After vi accepts my esc-key, I am in command-mode-1 (CM1).

Here is a list of my favorite commands for CM1:
  • esc
  • arrow-keys
  • a
  • i
  • o
  • u
  • x
  • dd
  • ZZ
  • :
The last command listed is colon and I use it to move from CM1 to CM2.

I like CM2 more that CM1 because vi tells me I am in CM2.

If I am in CM1 vi tells me nothing. I do not know if I am in CM1 or insert mode (IM).

So my favorite command is esc. This command works the same in all three modes. It sends me to CM1. If I am in CM1 and I press esc, vi will send me back to CM1. The esc-key is my favorite key in vi.

I can move from CM1 to IM by pressing a, i, or o. Also some others letters can be used. The letter a is used to append and i is used to insert so they are subtly different. The letter o is a bit like a except I can append after my current line. Just experiment with a,i, and o and you will see how they work. Most of the time I just use i.

The main actions which CM2 offer me are write and quit.

To write, I first move to CM1 by pressing esc. Then I move to CM2 by pressing :

Once I see the colon I know I am in CM2.

If I press enter, that is a mistake and CM2 will send me back to CM1.

If, however, I press w after the colon and then press enter, CM2 will write and then send me back to CM1.

So, this key sequence is very common:

esc, :w, enter

The above sequence is the same as File-Save in a GUI editor.

I can exit vi from CM1 by typing ZZ.

I can exit vi from CM2 by typing :q, enter.

I can exit vi from CM2 by typing :q!, enter.

I can exit vi from CM2 by typing :wq, enter. This is how I usually exit vi.

Common mistakes:
  • I am in CM1, but I assume I am in IM.
  • Delete characters by mistake while in CM1.
  • Open an enormous file.
  • Open a binary file.
  • Open file, make changes, go to lunch, go home.
  • Get dumped into the ed editor by vi.
Experiment with this command:
vi /tmp/hello.txt
Now you know enough vi to be really dangerous.



You are here: Linux101 > Shell 101 > shell101_vi
You can ask questions in Dan's Machine Learning Class Forum:
https://groups.google.com/forum/#!forum/dan101

syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me