Learning the vi vim editor commands on a linux server can be an absolute lifesaver when you're working remotely using nothing but SSH. There are two types of editors that come pre-installed on Every Linux server; nano and vim. While nano is simple, easy to learn and provides instant access to common options via shortcuts displayed at the bottom, it lacks the ability to extend itself through plugins. However, since Every Linux server comes with both, learning the basics of the vim editor is a much better investment for anyone who is going to be working with servers.
The main difference between nano and vim is that they operate differently. Nano is non-modal and doesn't require a shift in mindset. When you create/edit a File in nano, the shortcuts are available to you as soon as you begin. vim however operates in modes. This means you'll typically find yourself moving back and forth between normal mode and Insert Mode.
Normal mode: Default mode. All movements, deletions, copying, pasting take place here.
Insert Mode: to get into Insert Mode, Press i while in normal mode. You'll see -- insert -- appear at the bottom of your screen. From here you can type like normal.
Visual mode: to enter visual mode, Press v. Selects a block of text.
Command mode: enter command mode by pressing :. This allows you to save, Quit, search/replace within your document.
If you ever feel like you've become "stuck" in vim, hit Esc. It should send you back to normal mode.
Vi is the original minimal editor. vim (Vi IMproved) adds features such as: Syntax highlighting, Undo history, Plugin support. On Redhat Enterprise Linux (RHEL), Rocky, and Ubuntu systems, running "vi" actually runs "vim," regardless of which you choose. They function exactly alike for the purposes of this guide.
Examples
# Open or create a file
vim filename.txt
# Open with line numbers enabled from the start
vim -c "set number" filename.txt
# Also works with vi (opens vim on most systems)
vi filename.txt
There are many reasons why I prefer to use vim over nano, especially when working remotely with servers. One reason is because nano is not included in a minimal installation of RHEL/Rocky/Ubuntu. Because of this, nano would not be available on these systems for the average user/sys admin to use for making edits. Another reason is because nano is not modal, whereas vim has three modes (normal, insert, visual). Because of this, once you learn how to navigate and perform actions in the various modes of vim, it becomes much easier to use than nano. Also, nano has limited customization options compared to vim. Finally, when working with servers remotely (which is a big part of my job), having knowledge of how to use a powerful editor like vim makes me much more efficient.
vi vim Editor Commands: Open a File in vim
To open a File using vim, simply type vim, followed by the name of the File you wish to open (e.g., "vim example"). If the File already exists, vim will open it; if not, vim will create it upon First save. Upon opening, you will immediately be placed in normal mode.
Another line of content here.
"filename.txt" 2L, 54B
The status bar shows filename, line count, and file size. A new file shows [New File]. Do not start typing yet, you are in Normal mode.
Move into vim's Insert Mode
To move into Insert Mode from normal mode, simply Press i. Your cursor will now show --insert-- at the bottom of the screen. You may now type freely.
i
# Bottom of screen confirms:
-- INSERT --
a appends after cursor. o opens a new line below. O opens a new line above. Most of the time i is all you need.
Return to normal mode
To return to normal mode from Insert Mode, simply Press escape. The --insert-- indicator will disappear from the bottom of your screen.
Esc
# The -- INSERT -- indicator at the bottom disappears
Pressing Esc in Normal mode does nothing harmful. When in doubt, press it once to reset.
Save changes within vim without exiting vim
To save changes made to a File within vim without exiting vim, you may type :w, followed by enter. A confirmation message will appear at the bottom of your screen indicating that changes were saved and confirming the filename and number of bytes written.
:w
You may also create a backup copy of your File using :w newname.txt before creating your original File again. You may also override any read-only permissions on a File by adding ! After :w, but remember that you will need root-level privileges to do so.
Exit vim after saving changes
:wq will allow you to both save and Quit vim in one single step. Additionally, ZZ (all caps) does essentially the same thing without the colon.
:wq
# Same thing, shortcut (Normal mode, no colon needed)
ZZ
[returns to shell prompt]
:x also saves and quits, but only writes to disk if changes were made. On servers where scripts check file timestamps, :x is the cleaner choice over :wq.
Forcefully Exit vim without saving
If you have made modifications to a File and wish to force-Quit vim without saving those modifications, you may type :q!, followed by enter. Be aware that doing so will discard all unsaved changes with no warning and no opportunity to undo them. Once you Exit vim after using this option, your changes are lost forever. Therefore always run :w First if in doubt of whether or not you have made any changes before running :q to Exit vim. Use :q! Only when you are positive that you want to throw away your changes.
:q!
# Quit normally only works if no unsaved changes exist
:q
:q! discards all unsaved changes with no confirmation and no undo. Once you exit, those edits are gone. Always run :w first if there is any doubt, then :q to exit. Only use :q! when you are sure you want to throw away your changes.
Movement with hjkl keys
In addition to using your arrow keys to navigate throughout your document within vim, you may also use h j k l keys to move around in either direction (left/right/up/down). Hjkl keys provide more reliability due to potential issues involving older terminal environments or minimal SSH connections.
h ← move left one character
j ↓ move down one line
k ↑ move up one line
l → move right one character
Any movement within vim can be repeated by prefixing it with a number. Example: 5j will move down five lines. 10l will move right ten characters.
Moving cursor to Beginning & ending of lines
In longer config files, shell scripts or one-liners found within documents, it often proves beneficial to Jump straight to the Beginning/End of a Line rather than dragging your cursor across them using arrows. To Jump straight to the Beginning/End of a Line, Press 0 (zero) to Jump straight to the First character of the current Line or $ to Jump straight to the last character of the current Line.
0
# Jump to end of the current line
$
^ also jumps to the line start but skips leading whitespace. For indented files, ^ is often more useful than 0.
Jumping straight to First & last lines of files
To Jump directly to the First Line or last Line of a File without needing to scroll through its contents (as opposed to navigating through each individual Line), use gg to Jump directly to the First Line of a File and G to Jump directly to the last Line.
gg
# Jump to the last line of the file
G
# Jump to a specific line number e.g. line 42
42G
To Jump directly to any given Line number within a document/File, enter : followed by the number corresponding to the Line you'd like to Jump to and hit enter (example: :42).
Delete a Line with dd
One of the most useful vi vim editor commands is dd — how to delete a whole line in normal mode is easy, just hit dd. That removes that line from your file and puts it into a special area in memory known as the buffer. From there, you can copy that line elsewhere in your file or edit it. This command comes up frequently while trying to clean out configuration files or remove a block of comments.
dd
# Delete 3 lines starting from the current line
3dd
# Delete from cursor to end of line
D
In vim, delete and cut are the same thing. dd puts the line in the buffer and you can paste it with p. To delete a single character, use x.
Un-doing & Re-doing Actions in vim
To un-do your last action, in normal mode, simply hit the u. To un-do more actions, keep hitting u until you get back to where you want to be. Ctrl-r does the reverse; it re-dos an action that was previously un-done.
u
# Redo an undone change
Ctrl+r
# Undo all changes to the file since last save (revert to saved)
:e!
If you have made some edits to a file and don't like them, or if you need to go back to the last time you saved that file, type :e! in normal mode. That tells vim to load the file again from the hard drive and forget about anything you did after the last time you saved. Using :e! doesn't close vim. It loads the file again and gives you a fresh start.
Searching for a String/Pattern in vim
Among the essential vi vim editor commands, searching for something in a file using vim, you are in normal mode. Type /string (or whatever pattern you are looking for) and enter. All occurrences of the string will be highlighted and the cursor moved to the first instance. To find subsequent instances, hit n, to move backwards, hit N. If you wish to search upwards through the document instead of downwards, put a ? instead of / at the beginning of your search term.
/searchterm
# Search backward for a word
?searchterm
# Jump to next match
n
# Jump to previous match
N
# Clear search highlights after you are done
:nohlsearch
Vim search supports regex. /^server matches lines starting with "server". Run :noh to clear the highlights when done. Also see our guide on sed commands in Linux for more powerful search and replace from the terminal.
Replacing a String Across Entire Document in vim
The command %s/old/new/g will replace every instance of "old" with "new", throughout your entire document. Note: By default this will only replace the first "old" found on each line. To replace all "olds" found on each line, add the letter "g".
If you are doing this with a production configuration file that contains a large amount of commented-out code and active directives that contain the same string, use /gc. This allows you to replace individual strings selectively.
:%s/old/new/g
# Same but ask for confirmation before each replacement
:%s/old/new/gc
# Replace only on the current line
:s/old/new/g
# Replace between line 5 and line 20 only
:5,20s/old/new/g
y = replace this one
n = skip this one
a = replace all remaining
q = quit without any more replacements
Use /gc on production config files when the same string appears in both comments and active directives. Confirmation mode lets you replace selectively.
Copying & Pasting Lines in vim
Another key vi vim editor commands feature is yanking — in vim, we call copying "yanking." To yank the current line, use yy. When you want to paste, simply use p to place the copied line below the cursor, or P to place it above. If you want to yank multiple lines at once, prefix the line number you want with y.
yy
# Yank 3 lines starting from current position
3yy
# Paste below the current line
p
# Paste above the current line
P
dd also puts the deleted line in the buffer, so delete + p is how you cut and paste in vim. The buffer is overwritten on each yank or delete, so paste immediately after.
Opening vim w/ Line # enabled
You can tell vim to display line numbers by adding -c set number to your vim invocation. Or you can simply do :set number within vim itself anytime you are ready to see line numbers.
[root@server ~]# vim -c "set number" filename.txt
# Or toggle line numbers on from inside vim (Normal mode)
:set number
# Turn line numbers off
:set nonumber
2 # Deployment script
3 set -e
4
5 echo "Starting deployment..."
Adding items to .vimrc makes them available every time you invoke vim. Here is a sample .vimrc file for sysadmins & DevOps people:
[root@server ~]# vim ~/.vimrc
set number " show line numbers
set hlsearch " highlight search results
set ignorecase " case-insensitive search
set autoindent " auto indent new lines
set tabstop=4 " tab width of 4 spaces
set expandtab " convert tabs to spaces
vim usually comes installed on most server-based distributions. If not:
On Debian & Ubuntu: sudo apt-get install vim
On Fedora/RHEL/Rocky: sudo dnf install vim
Check by typing: vim --version. For more, see the official vim man page.
Always create a backup before making significant edits to important configurations files: cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak. That way even if things blow-up bigtime during your late night emergency fix session, you still have your working file. Remember also: :q! throws away everything you've done since opening your file (with no chance of undo).
People Also Ask
Press Esc, then type :wq to save and exit. Use :q! to quit without saving. If nothing changed, :q works too.
vi is the original minimal POSIX editor. vim adds syntax highlighting, multi-level undo, and plugin support. On most Linux distros, vi and vim point to the same binary.
Press Esc, then type :w and Enter. Vim saves the file and stays open. Use :wq to save and quit at the same time.
Type :%s/old/new/g to replace all matches in the file. Add c at the end to confirm each replacement before it happens.
Normal (default, navigate and run commands), Insert (press i to type), Command (press : to save, quit, search/replace). Press Esc from any mode to return to Normal.
Yes on most server distros. Desktop Ubuntu may only include vim-tiny. Install the full version with sudo apt install vim or sudo dnf install vim on RHEL/Fedora.
Basic Linux Commands |
Linux Commands for Beginners |
sed Commands in Linux |
find Command in Linux |
cat Command in Linux |
Linux Text Editors Cheat Sheet |
Linux Shell Scripting Cheat Sheet |
cron Command in Linux |
SSH Client Commands in Linux |
Linux Fundamentals
From your first terminal command to advanced sysadmin skills. Every guide here is written in plain English with real examples you can run right now.