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.
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
- 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
- Open the file:
vi myfile.txt. vi opens in command mode. - Press i to enter insert mode.
- Type your text, for example
my first line. - Press Esc to go back to command mode.
- Type
:wqand press Enter to save the file and quit (write and quit). You must be in command mode first.
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 this | In mode | What it does |
|---|---|---|
vi [/path/filename] | Shell | Opens or creates a file |
| i | Command | Switches to insert mode |
| Esc | Insert | Switches back to command mode |
:w | Command | Saves (writes) the file and keeps editing |
:wq | Command | Saves the file and quits vi |
:q | Command | Quits vi, but only if there are no unsaved changes |
:q! | Command | Quits vi and throws away unsaved changes |
| u | Command | Undoes the last change |
| dd | Command | Deletes the current line |
/word | Command | Searches 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.
:wsaves,:wqsaves and quits, and:q!quits without saving.- The bottom line shows
-- INSERT --when you're in insert mode. - When in doubt, press Esc.