Lesson 5 of 5 · Linux for DBAs

The vi Editor

How to create and edit files with vi, the text editor found on almost every Linux server: its two modes, saving, quitting, and the shortcuts to start with.

Beginner 6 sections 3 min read

What's vi

vi is the standard Linux text editor. You use it to add, delete, or change the contents of a file, right in the terminal.

Vim ("Vi IMproved") is a newer, enhanced version of vi. On many Linux systems, typing vi actually opens Vim, and everything in this lesson works the same in both.

vi [/path/filename]       # create a new file, or edit an existing one
$ vi myfile.txt           # open (or create) myfile.txt

vi's two modes

vi works in two modes, and the same key does different things in each. Knowing which mode you're in is the key to using vi.

Command mode vi starts here Insert mode type your text PRESS i PRESS ESC :w save :wq save and quit :q! quit, don't save
Command mode
Keys run commands: move around, delete, copy, paste, save, and quit. You can't type text into the file here. vi always opens in this mode.
Insert mode
Keys type text, like a regular editor. Enter starts a new line and the arrow keys move around.

Your first edit, step by step

  1. Open the file: vi myfile.txt. vi opens in command mode.
  2. Press i to enter insert mode.
  3. Type your text, for example my first line.
  4. Press Esc to go back to command mode.
  5. Type :wq and press Enter to save the file and quit (write and quit). You must be in command mode first.
~~~~~ "myfile.txt" [New] my first line ~~~~~ -- INSERT -- my first line ~~~~~ :wq 1. Opened: command mode 2. Pressed i: insert mode 3. Esc, then :wq to save
The tildes (~) mark empty lines past the end of the file.

How to tell which mode you're in

Look at the bottom line of the screen:

  • In insert mode, it shows -- INSERT --.
  • In command mode, it's blank or shows a message, such as the file name when you first open it.
  • When you type : in command mode, your command appears there as you type it, such as :wq.

vi shortcuts to start with

These are the commands you'll use most. Typical DBA edits, such as adding an entry to tnsnames.ora or changing a value in a script, need nothing more.

Type thisIn modeWhat it does
vi [/path/filename]ShellOpens or creates a file
iCommandSwitches to insert mode
EscInsertSwitches back to command mode
:wCommandSaves (writes) the file and keeps editing
:wqCommandSaves the file and quits vi
:qCommandQuits vi, but only if there are no unsaved changes
:q!CommandQuits vi and throws away unsaved changes
uCommandUndoes the last change
ddCommandDeletes the current line
/wordCommandSearches for "word"; press n for the next match

Commands that start with : run when you press Enter.

Key takeaways

  • vi opens in command mode. Press i to type, and Esc to stop typing.
  • :w saves, :wq saves and quits, and :q! quits without saving.
  • The bottom line shows -- INSERT -- when you're in insert mode.
  • When in doubt, press Esc.