How to Use vi Editor in Linux: Basic Commands and Tips
To use the
vi editor in Linux, open a terminal and type vi filename to edit or create a file. Use i to enter insert mode for typing, Esc to exit insert mode, and :wq to save and quit.Syntax
The basic syntax to open or create a file with vi is:
vi filename: Opens the file namedfilenameor creates it if it doesn't exist.- Modes:
vihas two main modes: command mode (default) and insert mode. - Press
ito enter insert mode to type text. - Press
Escto return to command mode. - Use commands starting with
:in command mode to save, quit, or perform other actions.
bash
vi filename
Example
This example shows how to create a file, add text, save it, and exit vi:
bash
vi example.txt # Inside vi: # 1. Press i to enter insert mode # 2. Type: Hello, vi editor! # 3. Press Esc to go back to command mode # 4. Type :wq and press Enter to save and quit
Output
The file 'example.txt' is created with the text 'Hello, vi editor!' saved inside.
Common Pitfalls
Beginners often get stuck because:
- They try to type text immediately without entering insert mode (
i). - They don't know how to exit insert mode (
Esckey). - They try to quit with
Ctrl+CorCtrl+Dinstead of using:wqor:q!.
Wrong way: Typing text in command mode does nothing.
Right way: Press i first, then type.
bash
Wrong (typing text directly):
vi file.txt
# Try typing text immediately (won't work)
Right:
vi file.txt
# Press i
# Type your text
# Press Esc
# Type :wq and EnterQuick Reference
| Command | Description |
|---|---|
| i | Enter insert mode to type text |
| Esc | Exit insert mode to command mode |
| :w | Save (write) the file |
| :q | Quit if no changes made |
| :q! | Quit without saving changes |
| :wq | Save and quit |
| dd | Delete current line |
| u | Undo last change |
Key Takeaways
Press i to enter insert mode before typing text in vi.
Use Esc to return to command mode to run commands.
Save and exit with :wq in command mode.
Use :q! to quit without saving if needed.
Practice basic commands to become comfortable with vi.