Learn to configure vim and nano text editors for efficient Linux system administration. Master keyboard shortcuts, create custom .vimrc configurations, and choose the right editor for different tasks.
Prerequisites
- Linux server with sudo access
- Basic command line knowledge
What this solves
Every Linux system administrator needs efficient text editing skills to manage configuration files, scripts, and logs. This tutorial shows you how to install, configure, and master both vim and nano editors, giving you the tools to handle any text editing task on your servers.
Step-by-step installation
Update system packages
Start by updating your package manager to ensure you get the latest editor versions.
sudo apt update && sudo apt upgrade -y
Install vim and nano
Install both editors to have options for different editing scenarios. Most systems include nano by default, but vim often needs installation.
sudo apt install -y vim nano
Set your default editor
Configure your preferred editor as the system default for git commits, cron jobs, and other tools.
sudo update-alternatives --install /usr/bin/editor editor /usr/bin/vim 1
sudo update-alternatives --install /usr/bin/editor editor /usr/bin/nano 2
sudo update-alternatives --config editor
Choose your preferred editor from the menu. You can also set the EDITOR environment variable in your ~/.bashrc file.
export EDITOR=vim
Master nano editor basics
Learn nano keyboard shortcuts
Nano displays its shortcuts at the bottom of the screen. The caret symbol (^) represents the Ctrl key.
| Shortcut | Action | Description |
|---|---|---|
| Ctrl+X | Exit | Exit nano (prompts to save if modified) |
| Ctrl+O | WriteOut | Save the file without exiting |
| Ctrl+W | Where Is | Search for text |
| Ctrl+\ | Replace | Search and replace text |
| Ctrl+G | Get Help | Display help information |
| Ctrl+K | Cut Text | Cut current line |
| Ctrl+U | UnCut | Paste cut text |
| Ctrl+T | To Spell | Check spelling |
Configure nano with .nanorc
Create a nano configuration file to customize your editing experience with syntax highlighting and useful options.
set tabsize 4
set autoindent
set linenumbers
set mouse
set softwrap
set titlecolor brightwhite,blue
set statuscolor brightwhite,green
set keycolor cyan
set functioncolor green
Include syntax highlighting
include "/usr/share/nano/*.nanorc"
These settings enable line numbers, auto-indentation, mouse support, and syntax highlighting for common file types.
Master vim editor essentials
Learn vim modes and navigation
Vim operates in different modes. Understanding these modes is crucial for effective editing.
| Mode | Purpose | How to Enter |
|---|---|---|
| Normal | Navigate and execute commands | Press Esc from any mode |
| Insert | Insert and edit text | Press i, a, o, or I, A, O |
| Visual | Select text | Press v for character, V for line |
| Command | Execute vim commands | Press : from normal mode |
Essential vim commands
Master these fundamental vim commands for efficient text editing and file management.
| Command | Mode | Action |
|---|---|---|
| :w | Command | Save file |
| :q | Command | Quit vim |
| :wq or :x | Command | Save and quit |
| :q! | Command | Quit without saving |
| dd | Normal | Delete current line |
| yy | Normal | Copy current line |
| p | Normal | Paste after cursor |
| /text | Normal | Search for "text" |
| :%s/old/new/g | Command | Replace all "old" with "new" |
| u | Normal | Undo last action |
| Ctrl+r | Normal | Redo last undone action |
Create a custom .vimrc configuration
Configure vim with a .vimrc file to improve usability and add syntax highlighting. This configuration works well for system administration tasks.
" Basic settings
set number " Show line numbers
set relativenumber " Show relative line numbers
set tabstop=4 " Tab width
set shiftwidth=4 " Indentation width
set expandtab " Convert tabs to spaces
set autoindent " Auto-indent new lines
set smartindent " Smart indentation
set hlsearch " Highlight search results
set incsearch " Incremental search
set ignorecase " Case-insensitive search
set smartcase " Case-sensitive if uppercase used
set mouse=a " Enable mouse support
set clipboard=unnamedplus " Use system clipboard
set backspace=indent,eol,start " Better backspace behavior
" Visual settings
syntax on " Enable syntax highlighting
set background=dark " Dark background
set ruler " Show cursor position
set showmatch " Show matching brackets
set cursorline " Highlight current line
set scrolloff=3 " Keep 3 lines visible when scrolling
" File handling
set noswapfile " Disable swap files
set nobackup " Disable backup files
set undofile " Enable persistent undo
set undodir=~/.vim/undodir " Undo directory
" Create undo directory if it doesn't exist
if !isdirectory($HOME."/.vim/undodir")
call mkdir($HOME."/.vim/undodir", "p")
endif
" Key mappings for easier editing
nnoremap :nohlsearch " Clear search highlighting
nnoremap :w " Ctrl+S to save
inoremap :wa " Ctrl+S to save in insert mode
Install vim plugins (optional)
For advanced users, install a plugin manager like vim-plug to extend vim functionality. This is particularly useful for development work.
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
Add these lines to your ~/.vimrc to install useful plugins:
call plug#begin('~/.vim/plugged')
" File tree explorer
Plug 'preservim/nerdtree'
" Status line
Plug 'vim-airline/vim-airline'
" Git integration
Plug 'tpope/vim-fugitive'
" Syntax checking
Plug 'vim-syntastic/syntastic'
call plug#end()
Install the plugins by opening vim and running :PlugInstall.
Choose the right editor for different tasks
When to use nano
Nano is ideal for quick edits and users new to Linux command line editing.
- Quick configuration file edits
- Writing simple scripts
- Editing crontab entries
- Emergency fixes when you need intuitive shortcuts
- Collaborative editing sessions where others might not know vim
When to use vim
Vim excels at complex editing tasks and provides powerful features for experienced users.
- Large file editing and navigation
- Complex search and replace operations
- Programming and script development
- Repetitive editing tasks (macros and commands)
- Working with multiple files simultaneously
- Remote editing over slow connections (efficient keystrokes)
Advanced editing techniques
Vim power user tips
These advanced techniques make vim incredibly efficient for system administration tasks.
# Edit multiple files
vim file1.conf file2.conf file3.conf
Open file at specific line
vim +25 /etc/nginx/nginx.conf
Execute command after opening
vim +"/search_term" logfile.txt
Open files in split windows
vim -o file1 file2 # horizontal split
vim -O file1 file2 # vertical split
Useful vim commands for sysadmins
These commands are particularly useful when working with configuration files and logs.
| Command | Purpose | Example Use Case |
|---|---|---|
| :set nu! | Toggle line numbers | Quickly reference line numbers in config files |
| :set paste | Enable paste mode | Paste configuration blocks without auto-formatting |
| :%s/^#//g | Remove # from line starts | Uncomment configuration sections |
| :g/pattern/d | Delete lines matching pattern | Remove error entries from logs |
| :sort | Sort selected lines | Organize configuration entries |
Verify your setup
Test both editors to ensure they're properly configured and working as expected.
# Check editor versions
vim --version | head -1
nano --version | head -1
Test nano configuration
echo "Testing nano configuration" | nano -T 4 -
Test vim configuration
vim -c "echo 'Vim configured successfully'" -c "sleep 2" -c "quit"
Verify default editor
echo $EDITOR
update-alternatives --display editor
Common issues
| Symptom | Cause | Fix |
|---|---|---|
| Vim opens in compatible mode | Missing .vimrc file | Create ~/.vimrc with set nocompatible |
| Nano doesn't show line numbers | Setting not enabled | Add set linenumbers to ~/.nanorc |
| Can't exit vim | Stuck in insert mode | Press Esc, then type :q! to quit without saving |
| Paste formatting is broken in vim | Auto-indent interfering | Use :set paste before pasting, :set nopaste after |
| Mouse doesn't work in vim | Mouse support disabled | Add set mouse=a to ~/.vimrc |
| Search highlighting won't clear | Persistent highlight setting | Type :nohlsearch or press Space (if configured) |
sudoedit filename for safer privilege escalation when editing system files.Next steps
Now that you have both editors configured, explore these related system administration topics:
- Configure shell aliases and functions for development productivity
- Configure Linux user and group management with sudo access control
- Configure Linux cron jobs and system task scheduling with best practices
- Advanced vim configuration with plugins and IDE features
- Configure tmux terminal multiplexer for efficient system administration
Running this in production?
Automated install script
Run this to automate the entire setup
#!/usr/bin/env bash
set -euo pipefail
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Script variables
SCRIPT_NAME="$(basename "$0")"
BACKUP_DIR="/tmp/editor-config-backup-$(date +%Y%m%d-%H%M%S)"
# Usage function
usage() {
echo "Usage: $SCRIPT_NAME [OPTIONS]"
echo "Configure vim and nano editors for system administration"
echo ""
echo "Options:"
echo " -e, --editor EDITOR Set default editor (vim|nano) [default: vim]"
echo " -u, --user USER Configure for specific user [default: current user]"
echo " -h, --help Show this help message"
echo ""
echo "Example: $SCRIPT_NAME --editor vim --user admin"
}
# Default values
DEFAULT_EDITOR="vim"
TARGET_USER="${SUDO_USER:-$USER}"
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
-e|--editor)
DEFAULT_EDITOR="$2"
if [[ "$DEFAULT_EDITOR" != "vim" && "$DEFAULT_EDITOR" != "nano" ]]; then
echo -e "${RED}Error: Editor must be 'vim' or 'nano'${NC}" >&2
exit 1
fi
shift 2
;;
-u|--user)
TARGET_USER="$2"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo -e "${RED}Error: Unknown option $1${NC}" >&2
usage
exit 1
;;
esac
done
# Cleanup function
cleanup() {
if [[ -d "$BACKUP_DIR" ]]; then
echo -e "${YELLOW}Cleaning up backup directory: $BACKUP_DIR${NC}"
rm -rf "$BACKUP_DIR"
fi
}
# Error handler
error_handler() {
echo -e "${RED}Error occurred on line $1. Attempting rollback...${NC}" >&2
if [[ -d "$BACKUP_DIR" ]]; then
echo -e "${YELLOW}Restoring from backup: $BACKUP_DIR${NC}"
if [[ -f "$BACKUP_DIR/.vimrc" ]]; then
cp "$BACKUP_DIR/.vimrc" "/home/$TARGET_USER/.vimrc" 2>/dev/null || true
fi
if [[ -f "$BACKUP_DIR/.nanorc" ]]; then
cp "$BACKUP_DIR/.nanorc" "/home/$TARGET_USER/.nanorc" 2>/dev/null || true
fi
if [[ -f "$BACKUP_DIR/.bashrc" ]]; then
cp "$BACKUP_DIR/.bashrc" "/home/$TARGET_USER/.bashrc" 2>/dev/null || true
fi
fi
cleanup
exit 1
}
trap 'error_handler $LINENO' ERR
trap cleanup EXIT
# Check prerequisites
echo -e "${BLUE}[1/8] Checking prerequisites...${NC}"
if [[ $EUID -ne 0 ]]; then
echo -e "${RED}Error: This script must be run as root or with sudo${NC}" >&2
exit 1
fi
if ! id "$TARGET_USER" &>/dev/null; then
echo -e "${RED}Error: User '$TARGET_USER' does not exist${NC}" >&2
exit 1
fi
# Auto-detect distribution
echo -e "${BLUE}[2/8] Detecting distribution...${NC}"
if [[ ! -f /etc/os-release ]]; then
echo -e "${RED}Error: Cannot detect distribution - /etc/os-release not found${NC}" >&2
exit 1
fi
. /etc/os-release
case "$ID" in
ubuntu|debian)
PKG_MGR="apt"
PKG_UPDATE="apt update -y"
PKG_INSTALL="apt install -y"
PKG_UPGRADE="apt upgrade -y"
;;
almalinux|rocky|centos|rhel|ol)
PKG_MGR="dnf"
PKG_UPDATE="dnf update -y"
PKG_INSTALL="dnf install -y"
PKG_UPGRADE="dnf upgrade -y"
;;
fedora)
PKG_MGR="dnf"
PKG_UPDATE="dnf update -y"
PKG_INSTALL="dnf install -y"
PKG_UPGRADE="dnf upgrade -y"
;;
amzn)
PKG_MGR="yum"
PKG_UPDATE="yum update -y"
PKG_INSTALL="yum install -y"
PKG_UPGRADE="yum upgrade -y"
;;
*)
echo -e "${RED}Error: Unsupported distribution: $ID${NC}" >&2
exit 1
;;
esac
echo -e "${GREEN}Detected: $PRETTY_NAME using $PKG_MGR${NC}"
# Update system packages
echo -e "${BLUE}[3/8] Updating system packages...${NC}"
$PKG_UPDATE
$PKG_UPGRADE
# Install vim and nano
echo -e "${BLUE}[4/8] Installing vim and nano...${NC}"
$PKG_INSTALL vim nano
# Create backup directory
mkdir -p "$BACKUP_DIR"
# Backup existing configurations
USER_HOME="/home/$TARGET_USER"
if [[ "$TARGET_USER" == "root" ]]; then
USER_HOME="/root"
fi
for config in .vimrc .nanorc .bashrc; do
if [[ -f "$USER_HOME/$config" ]]; then
cp "$USER_HOME/$config" "$BACKUP_DIR/"
fi
done
# Configure nano
echo -e "${BLUE}[5/8] Configuring nano...${NC}"
cat > "$USER_HOME/.nanorc" << 'EOF'
set tabsize 4
set autoindent
set linenumbers
set mouse
set softwrap
set titlecolor brightwhite,blue
set statuscolor brightwhite,green
set keycolor cyan
set functioncolor green
# Include syntax highlighting
include "/usr/share/nano/*.nanorc"
EOF
# Configure vim
echo -e "${BLUE}[6/8] Configuring vim...${NC}"
cat > "$USER_HOME/.vimrc" << 'EOF'
" Basic settings
set number " Show line numbers
set relativenumber " Show relative line numbers
set tabstop=4 " Tab width
set shiftwidth=4 " Indentation width
set expandtab " Convert tabs to spaces
set autoindent " Auto-indent new lines
set smartindent " Smart indentation
set hlsearch " Highlight search results
set incsearch " Incremental search
set ignorecase " Case-insensitive search
set smartcase " Case-sensitive if uppercase used
set mouse=a " Enable mouse support
set backspace=indent,eol,start " Better backspace behavior
" Visual settings
syntax on " Enable syntax highlighting
set background=dark " Dark background
set cursorline " Highlight current line
set showmatch " Show matching brackets
" Performance
set lazyredraw " Don't redraw during macros
set ttyfast " Fast terminal connection
" File handling
set encoding=utf-8 " Use UTF-8 encoding
set fileformat=unix " Use Unix line endings
" Status line
set laststatus=2 " Always show status line
set ruler " Show cursor position
EOF
# Set proper ownership and permissions
chown "$TARGET_USER:$TARGET_USER" "$USER_HOME/.vimrc" "$USER_HOME/.nanorc"
chmod 644 "$USER_HOME/.vimrc" "$USER_HOME/.nanorc"
# Set default editor using update-alternatives
echo -e "${BLUE}[7/8] Setting default editor...${NC}"
if command -v update-alternatives &> /dev/null; then
update-alternatives --install /usr/bin/editor editor /usr/bin/vim 10
update-alternatives --install /usr/bin/editor editor /usr/bin/nano 20
if [[ "$DEFAULT_EDITOR" == "vim" ]]; then
update-alternatives --set editor /usr/bin/vim
else
update-alternatives --set editor /usr/bin/nano
fi
fi
# Add EDITOR environment variable to .bashrc
if ! grep -q "export EDITOR=" "$USER_HOME/.bashrc" 2>/dev/null; then
echo "export EDITOR=$DEFAULT_EDITOR" >> "$USER_HOME/.bashrc"
chown "$TARGET_USER:$TARGET_USER" "$USER_HOME/.bashrc"
chmod 644 "$USER_HOME/.bashrc"
fi
# Verify installation
echo -e "${BLUE}[8/8] Verifying installation...${NC}"
vim --version | head -1
nano --version | head -1
# Check configuration files
if [[ -f "$USER_HOME/.vimrc" && -f "$USER_HOME/.nanorc" ]]; then
echo -e "${GREEN}Configuration files created successfully${NC}"
else
echo -e "${RED}Error: Configuration files not found${NC}" >&2
exit 1
fi
# Check default editor
if command -v update-alternatives &> /dev/null; then
CURRENT_EDITOR=$(update-alternatives --query editor | grep "Value:" | cut -d' ' -f2)
echo -e "${GREEN}Default editor set to: $CURRENT_EDITOR${NC}"
fi
echo -e "${GREEN}✓ Text editor configuration completed successfully!${NC}"
echo -e "${YELLOW}Note: Run 'source ~/.bashrc' or restart your shell to apply environment changes${NC}"
echo -e "${YELLOW}Backup created at: $BACKUP_DIR${NC}"
Review the script before running. Execute with: bash install.sh