Interactive Reference

Linux Complete Cheatsheet

A comprehensive reference covering file system structure, essential commands, system administration, networking, scripting, and advanced Linux topics โ€” from beginner to sysadmin level.

200+
Commands
18
Sections
50+
Examples
โˆž
Power
๐Ÿ—‚๏ธ
Linux File System Hierarchy (FHS)
Filesystem Hierarchy Standard โ€” how Linux organizes its directories
ESSENTIAL
โ„น๏ธ
Everything is a file in Linux. Devices, sockets, pipes โ€” all represented as files. The root of everything is / (the root directory). Unlike Windows, there are no drive letters โ€” one unified tree from /.
/ โ† Root: the top-level directory of the entire filesystem โ”œโ”€โ”€ bin/ Essential user command binaries (ls, cp, mv, cat, bash...) โ”œโ”€โ”€ boot/ Boot loader files, kernel images (vmlinuz), GRUB config โ”œโ”€โ”€ dev/ Device files โ€” hard drives (/dev/sda), terminals (/dev/tty), /dev/null, /dev/zero โ”œโ”€โ”€ etc/ System-wide configuration files (not binaries) โ”‚ โ”œโ”€โ”€ passwd User account info โ”‚ โ”œโ”€โ”€ shadow Encrypted passwords (root only) โ”‚ โ”œโ”€โ”€ fstab Filesystem mount table โ”‚ โ”œโ”€โ”€ hosts Static hostname to IP mappings โ”‚ โ”œโ”€โ”€ crontab System-wide cron jobs โ”‚ โ””โ”€โ”€ ssh/ SSH daemon configuration โ”œโ”€โ”€ home/ User home directories (/home/alice, /home/bob) โ”œโ”€โ”€ lib/ Shared libraries (.so files) needed by /bin and /sbin binaries โ”œโ”€โ”€ lib64/ 64-bit shared libraries โ”œโ”€โ”€ media/ Mount point for removable media (USB, CD-ROM) โ”œโ”€โ”€ mnt/ Temporary mount point for manually mounted filesystems โ”œโ”€โ”€ opt/ Optional add-on application packages (third-party software) โ”œโ”€โ”€ proc/ Virtual filesystem โ€” live info about processes and kernel (/proc/cpuinfo, /proc/meminfo) โ”œโ”€โ”€ root/ Home directory for the root (superuser) account โ”œโ”€โ”€ run/ Runtime data โ€” PIDs, lock files (cleared on reboot) โ”œโ”€โ”€ sbin/ System administration binaries (fdisk, iptables, mount) โ€” usually root-only โ”œโ”€โ”€ srv/ Data for services served by the system (web server files, FTP) โ”œโ”€โ”€ sys/ Virtual filesystem โ€” kernel & hardware info (sysfs) โ”œโ”€โ”€ tmp/ Temporary files โ€” cleared on reboot, world-writable โ”œโ”€โ”€ usr/ Secondary hierarchy for read-only user data and programs โ”‚ โ”œโ”€โ”€ bin/ Non-essential user commands (gcc, python, vim...) โ”‚ โ”œโ”€โ”€ lib/ Libraries for /usr/bin and /usr/sbin โ”‚ โ”œโ”€โ”€ local/ Locally compiled software (not from package manager) โ”‚ โ”œโ”€โ”€ sbin/ Non-essential system admin binaries โ”‚ โ””โ”€โ”€ share/ Architecture-independent data (man pages, icons, docs) โ””โ”€โ”€ var/ Variable data that changes at runtime โ”œโ”€โ”€ log/ System and application logs (/var/log/syslog, /var/log/auth.log) โ”œโ”€โ”€ spool/ Queued data (print, mail spools) โ”œโ”€โ”€ cache/ Application cache files โ””โ”€โ”€ www/ Web server document root (on some distros)
๐Ÿ”‘ Special Device Files
/dev/null โ€” Discard output (black hole)
/dev/zero โ€” Stream of null bytes
/dev/random โ€” Random data generator
/dev/sda โ€” First SATA/SCSI disk
/dev/sda1 โ€” First partition of sda
/dev/tty โ€” Current terminal device
/dev/stdin โ€” Standard input (fd 0)
/dev/stdout โ€” Standard output (fd 1)
๐Ÿ“‹ Important /proc Files
/proc/cpuinfo โ€” CPU details
/proc/meminfo โ€” Memory stats
/proc/uptime โ€” System uptime
/proc/version โ€” Kernel version
/proc/mounts โ€” Mounted filesystems
/proc/net/if_inet6 โ€” IPv6 interfaces
/proc/PID/ โ€” Info about process PID
/proc/loadavg โ€” Load average
โš™๏ธ Key /etc Files
/etc/passwd โ€” User accounts
/etc/shadow โ€” Password hashes
/etc/group โ€” Group definitions
/etc/hostname โ€” System hostname
/etc/hosts โ€” DNS override table
/etc/resolv.conf โ€” DNS server list
/etc/fstab โ€” Auto-mount table
/etc/sudoers โ€” Sudo access rules
๐Ÿ“
File & Directory Management
Create, copy, move, delete, and link files and directories
ESSENTIAL
CommandDescriptionExample
touch [file] Create empty file or update file timestamps. Creates the file if it doesn't exist. touch notes.txt
touch file1 file2 file3
mkdir [dir] Make directory. Use -p to create parent directories as needed (no error if exists). mkdir mydir
mkdir -p projects/web/src
cp src dst Copy files and directories.
-r recursive (copy directory tree)
-p preserve permissions, timestamps, ownership
-i interactive (prompt before overwrite)
-v verbose (show what's being copied)
-u only copy if source is newer
cp file.txt /backup/
cp -rp /var/www /backup/www-$(date +%F)
mv src dst Move or rename files/directories. Unlike cp, mv is instant for same-filesystem moves. mv old.txt new.txt
mv *.log /var/archive/
rm [file] Remove files/directories. โš  Permanent โ€” no Recycle Bin!
-r recursive (directories and contents)
-f force (no confirmation, ignore errors)
-i interactive (prompt each deletion)
-v verbose output
rm oldfile.txt
rm -rf /tmp/old-build/
rmdir [dir] Remove empty directory only. Use rm -rf for non-empty. rmdir empty_folder
ln src link Create links. Hard links (ln src link) share the same inode. Symbolic/soft links (ln -s src link) are like shortcuts โ€” can cross filesystems and link directories. ln -s /usr/bin/python3 ~/bin/python
ln data.bin data_hard.bin
rsync src dst Remote sync โ€” sync files efficiently, only transferring differences.
-a archive mode (recursive, preserves metadata)
-v verbose
-z compress during transfer
--delete delete files in dst not in src
--progress show transfer progress
rsync -avz /local/dir/ user@host:/remote/dir/
rsync -av --delete ~/docs/ /backup/docs/
stat [file] Display detailed file metadata: inode, permissions, size, access/modify/change times, link count. stat /etc/passwd
file [file] Determine file type by magic bytes (not extension). Works on binaries, scripts, images, etc. file unknown_binary โ†’ ELF 64-bit LSB executable
๐Ÿšจ
DANGER: rm -rf / or rm -rf /* will destroy your entire system. Modern versions of rm have --no-preserve-root guard. Always double-check paths before using rm -rf!
๐Ÿ‘๏ธ
File Viewing & Editing
Read, inspect, and edit file contents from the terminal
CommandDescriptionExample
cat [file] Concatenate and print file content. Also used to create files with <. -n shows line numbers. -A shows all chars including tabs/newlines. cat /etc/hosts
cat -n script.sh
cat file1 file2 > merged.txt
less [file] Page through file content (better than more). Controls: Space=next page, b=back, /pattern=search, n=next match, G=end, g=start, q=quit. less /var/log/syslog
more [file] Simple pager โ€” only scrolls forward. less is preferred for most uses. more /etc/passwd
head [file] Print first N lines of file. Default: 10 lines. -n 20 for first 20 lines. -c 100 for first 100 bytes. head -n 5 access.log
tail [file] Print last N lines. -f follows the file (live log monitoring). -F follows even if file is rotated. tail -f /var/log/nginx/error.log
tail -n 100 app.log
tee [file] Read from stdin and write to both stdout and file simultaneously. Useful in pipelines. ls -la | tee listing.txt
diff f1 f2 Show line-by-line differences between files. -u unified format (like git diff). -y side-by-side. diff -u original.conf new.conf
nano [file] Simple beginner-friendly terminal editor. Controls shown at bottom: Ctrl+O=save, Ctrl+X=exit, Ctrl+W=search, Ctrl+K=cut line, Ctrl+U=paste. nano /etc/hosts
wc [file] Word count โ€” shows lines, words, bytes. -l lines only, -w words only, -c bytes only. wc -l access.log
cat file | wc -c
xxd [file] Create a hexadecimal dump of a file. Useful for inspecting binary files and reverse engineering. xxd /bin/ls | head -20
๐Ÿ”
File Permissions & Ownership
Understanding and managing Linux file permissions (rwx model)
CRITICAL
๐Ÿ“–
Understanding ls -l output: A file listed as -rwxr-xr-- 1 alice devs 4096 Jun 10 file.sh โ€” The first character is type (-=file, d=dir, l=symlink). Then 3 groups of rwx: Owner (alice), Group (devs), Others. r=read(4), w=write(2), x=execute(1), -=not set.
Permission structure breakdownbash
# Format: [type][owner rwx][group rwx][other rwx]
  -  r w x  r - x  r - -
  โ”‚  โ”‚ โ”‚ โ”‚  โ”‚ โ”‚ โ”‚  โ”‚ โ”‚ โ”‚
  โ”‚  โ””โ”€โ”ดโ”€โ”˜  โ””โ”€โ”ดโ”€โ”˜  โ””โ”€โ”ดโ”€โ”˜
  โ”‚  Owner   Group  Others
  โ”‚
  โ””โ”€ Type: - file | d directory | l symlink | c char device | b block device

# Octal values:  r=4  w=2  x=1
# rwx = 4+2+1 = 7 | rw- = 4+2+0 = 6 | r-x = 4+0+1 = 5
# Common: 755 = rwxr-xr-x | 644 = rw-r--r-- | 777 = rwxrwxrwx | 600 = rw-------

# Special bits:
# SUID (4xxx) โ€” execute as file owner (e.g. /usr/bin/passwd)
# SGID (2xxx) โ€” execute as file group / new files inherit group
# Sticky (1xxx) โ€” only owner can delete file in dir (e.g. /tmp = 1777)
CommandDescriptionExample
chmod mode file Change file mode (permissions).
Numeric: use octal notation (755, 644, 600)
Symbolic: u=user, g=group, o=other, a=all
+=add, -=remove, ==set exactly
-R apply recursively
chmod 755 script.sh
chmod u+x,g-w deploy.sh
chmod -R 644 /var/www/html
chmod 4755 /usr/bin/myapp (SUID)
chown user:group file Change file owner and/or group. Requires root for changing owner. -R recursive. chown alice:devs project/
chown -R www-data:www-data /var/www
chown :newgroup file.txt
chgrp group file Change group ownership of file. Equivalent to chown :group file. chgrp developers config.yaml
umask [mask] Set the default permission mask for new files. The mask is subtracted from 666 (files) or 777 (dirs). Common: 022 โ†’ new files get 644, dirs get 755. umask โ†’ 0022
umask 027 (new files: 640)
getfacl [file] Get Access Control List (ACL) โ€” more granular permissions than the standard rwx model. getfacl /shared/project
setfacl options file Set ACL entries. -m modify, -x remove, -b remove all ACL entries. setfacl -m u:bob:rw- secret.txt
lsattr / chattr List/Change extended file attributes. +i makes file immutable (even root can't delete). +a append-only. chattr +i important.conf
lsattr important.conf
๐Ÿ”ข Common Permission Values
777 โ€” rwxrwxrwx (everyone full)
755 โ€” rwxr-xr-x (typical dir)
644 โ€” rw-r--r-- (typical file)
700 โ€” rwx------ (owner only)
600 โ€” rw------- (SSH keys)
640 โ€” rw-r----- (config files)
444 โ€” r--r--r-- (read-only all)
000 โ€” ---------- (no access)
โšก Quick Symbolic Chmod
chmod +x file โ€” add execute for all
chmod -x file โ€” remove execute for all
chmod u+x file โ€” add execute for owner
chmod go-w file โ€” remove write from group+others
chmod a=r file โ€” set all to read-only
chmod ug=rw,o=r โ€” complex assignment
โš™๏ธ
Process Management
Monitor, control, and manage running processes and jobs
CommandDescriptionExample
ps Process Status โ€” snapshot of current processes.
ps aux โ€” all processes (BSD style): a=all users, u=user-oriented, x=no terminal
ps -ef โ€” full format listing (POSIX)
ps -u alice โ€” processes by user
ps --forest โ€” show process tree
ps aux | grep nginx
ps -ef --forest
top Interactive process viewer (live). Keys: q=quit, k=kill, r=renice, M=sort by memory, P=sort by CPU, 1=show all CPUs, f=field selector. top -u www-data
top -b -n 1 > snapshot.txt
htop Enhanced interactive process viewer with colors, mouse support, tree view, easier to use than top. Install: apt install htop htop -u alice
kill [-signal] PID Send signal to process by PID. Default signal is TERM (15). Common: -9 SIGKILL (force, unblockable), -15 SIGTERM (graceful), -1 SIGHUP (reload config). kill 1234
kill -9 5678
kill -HUP $(cat /var/run/nginx.pid)
killall [name] Kill all processes matching a name. More convenient than finding PIDs manually. killall firefox
killall -9 zombie_process
pkill [pattern] Kill processes by pattern match (more flexible than killall). Supports regex and -u user filtering. pkill -f "python script.py"
pkill -u bob -TERM
pgrep [pattern] Find PIDs by process name/pattern. -l include name, -a full command line. pgrep -la nginx
pgrep -u root sshd
nice [-n N] cmd Start a command with specified priority (niceness). Range: -20 (highest) to 19 (lowest). Default: 0. Low priority = be "nicer" to other processes. nice -n 10 tar -czf backup.tar.gz /data
renice N -p PID Change priority of a running process. Requires root to decrease niceness (increase priority). renice +5 -p 1234
jobs / bg / fg Job control: jobs lists background/stopped jobs. bg %1 resumes job 1 in background. fg %1 brings to foreground. Ctrl+Z suspends current job. sleep 100 & (start in bg)
jobs
fg %1
nohup cmd & Run command that persists after logout (ignores SIGHUP). Output goes to nohup.out. See also: screen, tmux. nohup ./long_job.sh > job.log 2>&1 &
wait [PID] Wait for background process(es) to finish. Useful in scripts. ./task.sh & BPID=$! ; wait $BPID
๐Ÿ‘ค
User & Group Management
Create and manage users, groups, and privileges
CommandDescriptionExample
whoami Print the current user's name. Simple check for who you are. whoami โ†’ alice
id [user] Print user and group IDs (UID, GID, and supplementary groups). Critical for debugging permission issues. id alice โ†’ uid=1001(alice) gid=1001(alice) groups=1001(alice),27(sudo)
who / w who โ€” show logged-in users. w โ€” show logged-in users and what they're doing (more detailed). w
who -a
useradd [user] Create new user account.
-m create home directory
-s /bin/bash set default shell
-G sudo,docker add to supplementary groups
-c "Full Name" set GECOS comment
sudo useradd -m -s /bin/bash -G sudo alice
usermod [options] user Modify existing user account. -aG group append to group (use -a to avoid removing from existing groups!). -l new_name rename user. -L lock account. -U unlock. sudo usermod -aG docker alice
sudo usermod -L alice
userdel [user] Delete user account. -r also removes home directory and mail spool. sudo userdel -r olduser
passwd [user] Change password. Root can change any user's password. -l lock user. -u unlock. -e force expiry on next login. passwd (change own)
sudo passwd alice
groupadd [group] Create a new group. -g GID specify numeric group ID. sudo groupadd developers
groups [user] List all groups a user belongs to. groups alice โ†’ alice sudo docker
sudo [cmd] Execute command as superuser (root). sudo -i interactive root shell. sudo -u alice cmd run as another user. sudo !! re-run last command with sudo. sudo apt update
sudo -i
sudo su - alice
su [user] Switch user. su - becomes root (reads root's profile). su - alice switches to alice with her environment. su - alice
su - (become root)
last [user] Show login history from /var/log/wtmp. lastb shows failed login attempts. lastlog shows last login for each user. last -10
lastb | head -20
๐Ÿ“Š
System Information
Monitor hardware, memory, CPU, and kernel information
CommandDescriptionExample
uname Print kernel/OS info. -a all info, -r kernel release, -m machine hardware (x86_64), -s kernel name, -n hostname. uname -a โ†’ Linux host 5.15.0 #1 SMP x86_64 GNU/Linux
hostname Show or set system hostname. -I show all IP addresses. -f fully qualified domain name (FQDN). hostname -I
uptime Show how long the system has been running, number of users, and 1/5/15-minute load averages. Load > number of CPU cores = overloaded. uptime โ†’ 14:32:01 up 5 days, 2:14, 2 users, load average: 0.52, 0.38, 0.29
free Display memory usage (RAM + swap). -h human-readable. -m in MB. -g in GB. -s 2 update every 2 seconds. free -h
lscpu Detailed CPU architecture information: cores, threads, speed, cache, virtualization support, NUMA topology. lscpu | grep -E "^CPU|Thread|Core|Socket"
lsmem List ranges of available memory from the system. More detailed than free. lsmem
lspci List all PCI devices (graphics cards, network adapters, etc.). -v verbose, -k show kernel driver. lspci -k | grep -A2 "VGA"
lsusb List USB devices connected to the system. lsusb -v | less
lshw Comprehensive hardware information (may need to install). -short summary format. -class disk filter by class. sudo lshw -short
vmstat Virtual memory stats โ€” processes, memory, swap, I/O, CPU. vmstat 1 5 โ€” print 5 samples every 1 second. vmstat 1 10
iostat I/O statistics โ€” CPU usage and I/O activity per disk/partition. -x extended stats. -h human-readable. iostat -xh 2
dmesg Print kernel ring buffer messages โ€” hardware detection, driver errors, boot messages. -T human-readable timestamps. --level=err only errors. dmesg -T | tail -50
dmesg | grep -i "error\|fail"
journalctl Query systemd journal logs. -f follow live. -u nginx filter by unit. -b current boot. --since "1 hour ago" time filter. -p err priority filter. journalctl -u sshd -f
journalctl -b -p err
journalctl --since "2024-01-01" --until "2024-01-02"
๐Ÿ”ง
Service Management (systemctl)
Control system services and daemons with systemd
โ„น๏ธ
systemd is the init system and service manager used by most modern Linux distributions (Ubuntu, Debian, Fedora, CentOS, Arch). It manages processes, mounts, timers, and more via "units." Service unit files are stored in /etc/systemd/system/ and /lib/systemd/system/.
CommandDescription
sudo systemctl start nginxStart a service (immediately)
sudo systemctl stop nginxStop a running service
sudo systemctl restart nginxStop then start the service
sudo systemctl reload nginxReload config without stopping (if supported)
systemctl status nginxShow service status, recent logs, and PID
sudo systemctl enable nginxEnable service to auto-start at boot
sudo systemctl disable nginxDisable auto-start at boot
systemctl is-active nginxReturns "active" or "inactive" โ€” useful in scripts
systemctl is-enabled nginxCheck if service is enabled at boot
systemctl list-units --type=serviceList all loaded service units
systemctl list-units --failedList all failed units
sudo systemctl daemon-reloadReload systemd config after creating/modifying unit files
sudo systemctl rebootReboot the system
sudo systemctl poweroffShutdown the system
Creating a custom systemd service unitini
# /etc/systemd/system/myapp.service
[Unit]
Description=My Application Server
After=network.target        # Start after network is up

[Service]
Type=simple
User=www-data
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node /opt/myapp/server.js
Restart=on-failure         # Auto-restart on crash
RestartSec=5
Environment=NODE_ENV=production
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target  # Enable for multi-user mode
๐ŸŒฟ
Environment Variables
Shell variables that configure the environment for processes
CommandDescriptionExample
env Print all environment variables and their values. Also used to run a command in a modified environment. env
env PATH=/custom:$PATH ./script.sh
printenv [VAR] Print value of an environment variable. Safer than echo $VAR for scripting. printenv PATH
printenv HOME USER SHELL
export VAR=value Set and export an environment variable (makes it available to child processes). Without export, it's only a shell variable. export DB_HOST=localhost
export PATH="$HOME/.local/bin:$PATH"
unset VAR Remove a variable from the environment. unset TEMP_API_KEY
echo $VAR Display the value of a variable. Use double quotes to preserve spaces: "$VAR". echo $HOME โ†’ /home/alice
echo "Hello $USER!"
set List all shell variables (both environment and local). Also used to set shell options (set -e exit on error, set -x debug mode). set | grep PATH
๐Ÿ”‘ Important Env Variables
$HOME โ€” Current user's home dir
$PATH โ€” Colon-separated binary search paths
$USER โ€” Current username
$SHELL โ€” Path to current shell
$PWD โ€” Current working directory
$OLDPWD โ€” Previous directory
$LANG โ€” Current locale setting
$TZ โ€” Timezone (e.g. UTC, Asia/Jakarta)
$EDITOR โ€” Default text editor
$TERM โ€” Terminal type (xterm-256color)
$? โ€” Exit status of last command
$$ โ€” PID of current shell
$! โ€” PID of last background process
๐Ÿ“„ Startup Files
Bash login shell:
/etc/profile โ†’ system-wide
~/.bash_profile โ†’ user-specific
~/.bashrc โ†’ interactive non-login
~/.bash_logout โ†’ on logout

Zsh:
~/.zshrc โ†’ interactive shell
~/.zprofile โ†’ login shell
๐ŸŒ
Network Commands
Diagnose and manage network interfaces, connections, and traffic
ADMIN
CommandDescriptionExample
ip addr Show IP addresses and network interfaces. Modern replacement for ifconfig. Also: ip link (interfaces), ip route (routing table), ip neigh (ARP table). ip addr show eth0
ip route show
ip link set eth0 up
ifconfig [iface] Legacy interface configurator. Still common on older systems. Install with net-tools package. ifconfig eth0
ifconfig eth0 192.168.1.100 netmask 255.255.255.0
ping host Test connectivity to a host via ICMP echo. -c 4 send 4 packets, -i 0.2 interval 0.2s, -s 1000 packet size 1000 bytes. ping -c 4 google.com
ping6 ::1
traceroute host Trace the route packets take to a host, showing each hop. tracepath is an alternative that doesn't require root. traceroute google.com
traceroute -n 8.8.8.8
ss [options] Socket Statistics โ€” modern replacement for netstat. -t TCP, -u UDP, -l listening, -n numeric, -p show process. ss -tlnp (listening TCP with PIDs)
ss -s (summary stats)
netstat Legacy network stats. Common: -tulnp (listening TCP/UDP with process). Deprecated in favor of ss. netstat -tulnp | grep 80
dig domain DNS lookup tool. More detailed than nslookup. @8.8.8.8 use specific DNS server. -t MX query specific record type. dig google.com A
dig @1.1.1.1 example.com MX
dig +short google.com
nslookup domain Query DNS servers interactively or one-shot. dig is preferred for scripting. nslookup github.com 8.8.8.8
curl [url] Transfer data using URLs. Very versatile.
-o file save to file
-L follow redirects
-H "Header: val" send header
-d "data" POST body
-X POST/PUT/DELETE HTTP method
-u user:pass basic auth
-I headers only
-k skip SSL verification
curl -sL https://api.github.com/repos/cli/cli | jq .name
curl -X POST -H "Content-Type: application/json" -d '{"key":"val"}' https://api.example.com/data
wget [url] Download files from web. -O file save as specific filename. -r recursive download. -q quiet mode. --limit-rate=1m rate limit. wget -O install.sh https://get.docker.com
wget -q --show-progress https://example.com/large.iso
nc (netcat) The "Swiss army knife" of networking. TCP/UDP connections, port scanning, banners, file transfer, simple servers. nc -zv google.com 443 (port check)
nc -l 8080 (simple listener)
nmap [host] Network/port scanner. -p 1-1000 port range. -sV version detection. -O OS detection. Use only on hosts you own! nmap -sV -p 22,80,443 192.168.1.1
๐Ÿ”’
SSH & Remote Access
Secure Shell for remote login, tunneling, and file transfer
CommandDescriptionExample
ssh user@host Connect to remote host. -p 2222 custom port. -i key.pem identity file. -v verbose (debug). -A forward agent. -X X11 forwarding. ssh alice@192.168.1.50
ssh -i ~/.ssh/mykey.pem -p 2222 ubuntu@server.com
ssh-keygen Generate SSH key pair. -t ed25519 (recommended) or -t rsa -b 4096. -C "comment" add comment. -f filename output file. ssh-keygen -t ed25519 -C "alice@work"
ssh-copy-id user@host Copy your public key to remote host's ~/.ssh/authorized_keys. Enables passwordless login. ssh-copy-id -i ~/.ssh/id_ed25519.pub alice@server.com
scp src dst Secure copy files over SSH. -r recursive. -P 2222 port. Format: user@host:/path for remote. scp report.pdf alice@server:/home/alice/
scp -r user@host:/var/log/ ./logs/
sftp user@host Secure FTP interactive file transfer over SSH. Commands: put, get, ls, cd, mkdir, rm, bye. sftp alice@server.com
ssh -L local:remote Local port forwarding (tunnel). Forward local port to remote service through SSH. -L 8080:localhost:80 means: local:8080 โ†’ server:80 ssh -L 5432:localhost:5432 user@server (tunnel remote DB)
ssh -R remote:local Remote port forwarding โ€” expose a local port on the remote server. Useful for exposing local dev to the internet. ssh -R 8080:localhost:3000 user@server
~/.ssh/config โ€” SSH client configurationssh_config
# Allows: ssh prod  (instead of ssh -i ~/.ssh/mykey.pem -p 22 ubuntu@203.0.113.5)
Host prod
    HostName    203.0.113.5
    User        ubuntu
    IdentityFile ~/.ssh/mykey.pem
    Port        22

Host bastion
    HostName    10.0.0.1
    User        admin
    IdentityFile ~/.ssh/bastion.pem

# Jump through bastion to reach internal hosts
Host internal-*
    ProxyJump   bastion
    User        ubuntu
    IdentityFile ~/.ssh/internal.pem

# Global settings
Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3
    AddKeysToAgent  yes
๐Ÿ›ก๏ธ
Firewall (UFW & iptables)
Control network traffic with firewall rules
UFW โ€” Uncomplicated Firewall (Ubuntu/Debian)bash
# Enable/disable UFW
sudo ufw enable
sudo ufw disable
sudo ufw status verbose

# Allow and deny rules
sudo ufw allow 22               # Allow SSH
sudo ufw allow 80/tcp           # Allow HTTP
sudo ufw allow 443              # Allow HTTPS
sudo ufw allow from 192.168.1.0/24  # Allow from subnet
sudo ufw deny 23                # Deny telnet
sudo ufw delete allow 80        # Remove a rule
sudo ufw reset                  # Reset to defaults

# Allow app profiles
sudo ufw app list
sudo ufw allow 'Nginx Full'     # Allow both HTTP+HTTPS for nginx
sudo ufw allow 'OpenSSH'
iptables โ€” Low-level firewall rulesbash
# List rules with line numbers
sudo iptables -L -n -v --line-numbers

# Allow established connections (critical!)
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow loopback
sudo iptables -A INPUT -i lo -j ACCEPT

# Allow SSH, HTTP, HTTPS
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Drop everything else
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP

# Flush all rules
sudo iptables -F
๐Ÿ’พ
Disk & Storage Management
Manage disks, partitions, filesystems, and mounts
CommandDescriptionExample
df Disk filesystem usage โ€” shows used/available space per mounted filesystem. -h human-readable. -T show filesystem type. -i inode usage. df -hT
df -h /var
du Disk usage of files and directories. -h human-readable. -s summary total only. -d 1 max depth 1. --max-depth. du -sh /var/log/*
du -d 1 -h /home | sort -rh | head -10
lsblk List block devices in tree format. Shows disks, partitions, sizes, mount points. -f filesystem info. lsblk -f
fdisk [device] Partition table manipulator (MBR/GPT). Interactive menu-driven tool for creating/deleting partitions. -l list all partition tables. sudo fdisk -l
sudo fdisk /dev/sdb
parted [device] Advanced partition editor โ€” supports GPT and large disks. Can resize partitions. sudo parted /dev/sdb print
mkfs [device] Format partition with a filesystem. Variants: mkfs.ext4, mkfs.xfs, mkfs.vfat. sudo mkfs.ext4 /dev/sdb1
sudo mkfs.xfs -L "data" /dev/sdc1
mount device dir Mount a filesystem to a directory. -t ext4 specify type. -o ro read-only. mount -a mount all from fstab. sudo mount /dev/sdb1 /mnt/data
sudo mount -o loop image.iso /mnt/cdrom
umount device/dir Unmount a filesystem. Must not be in use. -l lazy unmount (when busy). sudo umount /mnt/data
sudo umount -l /dev/sdb1
fsck [device] Filesystem check and repair. Run on unmounted filesystem only. -a auto-repair. sudo fsck -a /dev/sdb1
blkid Show block device attributes โ€” UUID, filesystem type, label. Use UUID in fstab instead of device names (which can change). sudo blkid
sudo blkid /dev/sda1
dd if= of= Disk duplicator โ€” low-level copy. Can clone disks, create ISOs, zero-fill drives. Very powerful โ€” double-check if= and of= parameters! sudo dd if=/dev/sda of=/dev/sdb bs=4M status=progress
sudo dd if=/dev/zero of=/dev/sdb bs=1M (wipe)
swap Create and manage swap: mkswap /dev/sdb2 then swapon /dev/sdb2. Check with swapon --show. sudo mkswap /dev/sdb2
sudo swapon /dev/sdb2
๐Ÿ“ฆ
Archive & Compression
Pack, compress, extract, and transfer file archives
tar โ€” Tape Archive (most common)bash
# Key flags: c=create, x=extract, t=list, v=verbose, f=file, z=gzip, j=bzip2, J=xz

# CREATE archives
tar -czf archive.tar.gz /path/to/dir/     # gzip compressed
tar -cjf archive.tar.bz2 /path/to/dir/   # bzip2 (better compression)
tar -cJf archive.tar.xz /path/to/dir/    # xz (best compression)
tar -cf archive.tar /path/to/dir/         # no compression

# EXTRACT archives
tar -xzf archive.tar.gz                   # extract gzip
tar -xzf archive.tar.gz -C /target/dir/  # extract to specific dir
tar -xjf archive.tar.bz2                  # extract bzip2

# LIST contents (without extracting)
tar -tzf archive.tar.gz                   # list gzip archive
tar -tf archive.tar | head -20            # list first 20 items

# Extract specific file from archive
tar -xzf archive.tar.gz path/to/specific/file.txt
CommandDescriptionExample
gzip / gunzip Compress/decompress with gzip. -k keep original. -9 max compression. -d decompress. gzip -k largefile.log
gunzip file.gz
bzip2 / bunzip2 Compress with bzip2 โ€” better compression than gzip but slower. Creates .bz2 files. bzip2 -k bigfile.txt
bunzip2 file.bz2
xz / unxz Best general-purpose compression. Slower but produces smallest files. Creates .xz files. Used for Linux kernel distribution. xz -k -9 hugefile
unxz file.xz
zip / unzip Create/extract ZIP archives (cross-platform compatible). -r recursive. -l list contents. -d file extract specific file. zip -r backup.zip ./project/
unzip -d /target/ archive.zip
zcat / zless Read gzip files without extracting. zcat prints content, zless pages through it. Also: zgrep, zdiff. zcat access.log.gz | grep "404"
zless /var/log/syslog.1.gz
๐Ÿ“
Text Processing
grep, sed, awk, cut, sort, uniq, tr โ€” the core text manipulation toolkit
POWERFUL
grep โ€” Global Regular Expression Printbash
# Flags: -i case-insensitive | -r recursive | -n line numbers | -v invert
#        -c count matches | -l list filenames | -E extended regex | -P Perl regex
#        -w whole word | -A N after N lines | -B N before N lines | -C N context

grep "error" /var/log/syslog              # basic search
grep -i "error" app.log                    # case-insensitive
grep -rn "TODO" ./src/                      # recursive with line numbers
grep -v "#" /etc/nginx/nginx.conf           # invert (exclude comments)
grep -E "(ERROR|WARN|FATAL)" app.log        # extended regex OR
grep -P "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" log  # Perl regex (IP addresses)
grep -C 3 "panic" kernel.log               # 3 lines context around match
grep -c "200 OK" access.log                  # count of matching lines
grep -l "password" /etc/*.conf               # list files with match
sed โ€” Stream Editorbash
# sed 's/PATTERN/REPLACEMENT/FLAGS'  โ€” substitution
sed 's/foo/bar/' file.txt             # replace first occurrence per line
sed 's/foo/bar/g' file.txt            # replace ALL occurrences (global)
sed 's/foo/bar/gi' file.txt           # case-insensitive global replace
sed -i 's/old/new/g' file.txt         # in-place edit (modifies file!)
sed -i.bak 's/old/new/g' file.txt     # in-place with .bak backup
sed -n '5,10p' file.txt               # print lines 5-10 only
sed '/^#/d' config.conf               # delete lines starting with #
sed '/^$/d' file.txt                  # delete empty lines
sed 's/[[:space:]]*$//' file.txt      # strip trailing whitespace
# Multi-expression:
sed -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt
awk โ€” Pattern scanning and processing languagebash
# awk 'PATTERN { ACTION }' file  โ€” NR=line num, NF=field count, $1-$N=fields
awk '{print $1}' file.txt              # print first column
awk '{print $1, $3}' access.log        # print columns 1 and 3
awk -F: '{print $1, $6}' /etc/passwd   # use : as delimiter (username, home)
awk 'NR==5' file.txt                   # print only line 5
awk 'NR>=5 && NR<=10' file.txt         # print lines 5 to 10
awk '/ERROR/ {print NR": "$0}' app.log  # print ERROR lines with line num
awk '{sum+=$3} END {print sum}' data    # sum column 3
awk '{count[$1]++} END {for(k in count) print k, count[k]}' log # frequency count
awk '$5 > 100' metrics.txt             # rows where field 5 > 100
awk 'BEGIN{OFS=","} {print $1,$2,$3}' file.txt  # CSV output
CommandDescriptionExample
cut Cut fields from each line. -d ':' delimiter. -f 1,3 fields 1 and 3. -c 1-10 characters 1-10. cut -d: -f1,6 /etc/passwd
cut -c1-80 longfile.txt
sort Sort lines. -r reverse. -n numeric. -u unique. -k 2 sort by field 2. -t ':' delimiter. -h human-numeric (1K, 2M). sort -rn -k3 data.txt
du -sh * | sort -rh
uniq Remove adjacent duplicate lines. Must sort first for global dedup. -c count occurrences. -d only show duplicates. -u only show unique. sort access.log | uniq -c | sort -rn | head -10
tr Translate or delete characters. -d delete chars. -s squeeze repeated. Works on stdin only. echo "hello" | tr 'a-z' 'A-Z'
cat file | tr -d '\r' (remove Windows line endings)
paste Merge lines from multiple files side by side. -d ',' delimiter. paste -d, names.txt scores.txt
join Join lines of two files on a common field (like SQL JOIN). Files must be sorted on the join field. join -t: -1 1 -2 1 file1.txt file2.txt
jq JSON processor โ€” filter, transform, and format JSON. Essential for API work. Must install separately. curl -s api.github.com/users/torvalds | jq '.name, .public_repos'
cat data.json | jq '.items[] | select(.active==true)'
๐Ÿ“ฅ
Package Management
Install, update, and remove software across major Linux distributions
๐ŸŸก APT (Debian, Ubuntu)
sudo apt update โ€” refresh package lists
sudo apt upgrade โ€” upgrade all packages
sudo apt full-upgrade โ€” upgrade + remove obsolete
sudo apt install nginx โ€” install package
sudo apt remove nginx โ€” remove (keep config)
sudo apt purge nginx โ€” remove + delete config
sudo apt autoremove โ€” remove unused deps
apt search keyword โ€” search packages
apt show nginx โ€” show package details
apt list --installed โ€” list installed
dpkg -l โ€” list all dpkg packages
dpkg -i package.deb โ€” install .deb file
๐Ÿ”ต DNF/YUM (RHEL, Fedora, CentOS)
sudo dnf check-update โ€” check for updates
sudo dnf update โ€” upgrade all
sudo dnf install nginx โ€” install
sudo dnf remove nginx โ€” remove
sudo dnf autoremove โ€” remove unused deps
dnf search keyword โ€” search
dnf info nginx โ€” package info
dnf list installed โ€” list installed
dnf provides /usr/bin/python3 โ€” which pkg provides file
rpm -ivh package.rpm โ€” install .rpm
rpm -qa โ€” list all installed RPMs
๐Ÿ”ท Pacman (Arch Linux, Manjaro)
sudo pacman -Syu โ€” sync + upgrade all
sudo pacman -S nginx โ€” install
sudo pacman -R nginx โ€” remove
sudo pacman -Rs nginx โ€” remove + unused deps
pacman -Ss keyword โ€” search repos
pacman -Si nginx โ€” package info
pacman -Q โ€” list installed
pacman -Qe โ€” explicitly installed
pacman -Sc โ€” clean package cache
yay -S package โ€” AUR helper (community)
๐ŸŸฃ Snap & Flatpak (Universal)
Snap:
snap find keyword โ€” search Snap Store
sudo snap install code --classic โ€” install
sudo snap remove code โ€” remove
snap list โ€” list installed
sudo snap refresh โ€” update all snaps

Flatpak:
flatpak search keyword โ€” search
flatpak install flathub app.id โ€” install
flatpak update โ€” update all
flatpak list โ€” list installed
๐Ÿ”€
Pipes, Redirection & I/O
Connect commands and control input/output streams
๐Ÿ“–
Every process has three standard streams: stdin (fd 0, keyboard), stdout (fd 1, terminal), stderr (fd 2, terminal). Redirection operators control where these streams go.
OperatorDescriptionExample
| Pipe โ€” send stdout of left command to stdin of right command. Can chain multiple pipes. cat access.log | grep "404" | wc -l
ps aux | sort -rk3 | head -10
> Redirect stdout to file โ€” overwrites existing content. ls -la > listing.txt
echo "hello" > greet.txt
>> Append stdout to file โ€” does not overwrite, adds to end. echo "line" >> log.txt
date >> timestamps.log
< Redirect stdin from file โ€” feed a file as input to a command. sort < unsorted.txt > sorted.txt
mysql -u root db < dump.sql
2> Redirect stderr to file. The 2 refers to file descriptor 2 (stderr). find / -name "*.conf" 2> errors.txt
2>&1 Redirect stderr to stdout โ€” merge error output with standard output. Allows piping both. ./script.sh > output.log 2>&1
./script.sh &> combined.log
&> Redirect both stdout and stderr to file (shorthand for >file 2>&1). Bash only. command &> all_output.log
<<EOF Here-document โ€” multi-line string as stdin. Text is fed until the EOF marker. Used in scripts. cat <<EOF
> line1
> line2
> EOF
<<<"string" Here-string โ€” feed a single string to stdin. Cleaner than echo "x" | cmd. grep "foo" <<<"foo bar baz"
$(cmd) Command substitution โ€” replace $(cmd) with the output of cmd. Nests cleanly unlike backticks. echo "Today is $(date +%F)"
FILES=$(ls *.log); wc -l $FILES
Useful pipe patternsbash
# Top 10 largest files in current directory
du -ah . | sort -rh | head -10

# Count unique IP addresses in access.log
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -20

# Find and kill processes by name
ps aux | grep "[n]ode" | awk '{print $2}' | xargs kill -9

# Watch live HTTP errors (follow + filter)
tail -f /var/log/nginx/access.log | grep --line-buffered " 5[0-9][0-9] "

# Backup and compress in one command
tar -czf - /var/www | ssh user@backup-server "cat > /backup/www-$(date +%F).tar.gz"
โฐ
Cron Jobs โ€” Task Scheduling
Schedule recurring tasks using the cron daemon
Crontab syntaxbash
#  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ minute (0 - 59)
#  โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ hour (0 - 23)
#  โ”‚  โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€ day of month (1 - 31)
#  โ”‚  โ”‚  โ”‚  โ”Œโ”€โ”€ month (1 - 12 or jan-dec)
#  โ”‚  โ”‚  โ”‚  โ”‚  โ”Œโ”€ day of week (0-7, both 0&7=Sunday, or mon-sun)
#  โ”‚  โ”‚  โ”‚  โ”‚  โ”‚
#  *  *  *  *  *  command to execute

# EXAMPLES:
0  2  *  *  *  /usr/bin/backup.sh            # Every day at 02:00
*/5 * *  *  *  /usr/bin/check_disk.sh        # Every 5 minutes
0  9  *  *  1  /usr/bin/weekly_report.sh     # Every Monday at 09:00
0  0  1  *  *  /usr/bin/monthly_cleanup.sh   # 1st of every month at midnight
30 18 *  *  1-5 /usr/bin/eod_report.sh       # Mon-Fri at 18:30
@reboot         /usr/bin/startup_task.sh     # On every system boot
@daily          /usr/bin/daily_task.sh        # Once a day (0 0 * * *)
@weekly         /usr/bin/weekly_task.sh       # Once a week
@monthly        /usr/bin/monthly_task.sh      # Once a month
CommandDescription
crontab -eEdit your crontab (opens in $EDITOR)
crontab -lList current user's cron jobs
crontab -rRemove (delete) all your cron jobs
sudo crontab -u alice -lList cron jobs for another user
cat /etc/crontabSystem-wide crontab (has user field)
ls /etc/cron.d/ /etc/cron.daily/ /etc/cron.weekly/Directory-based scheduled scripts
โš ๏ธ
Best practices: Always use absolute paths in cron jobs (e.g. /usr/bin/python3 not just python3) since cron runs with a minimal PATH. Redirect output: * * * * * /script.sh >> /var/log/myjob.log 2>&1. Use crontab.guru to verify expressions.
๐Ÿ“œ
Shell Scripting (Bash)
Automate tasks with bash scripts โ€” variables, conditions, loops, functions
AUTOMATION
Bash scripting essentialsbash
#!/bin/bash
# ^ Shebang: tells OS which interpreter to use
# Make executable: chmod +x script.sh

# โ”€โ”€ Safe mode flags โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
set -euo pipefail    # -e: exit on error, -u: error on unset var, -o pipefail: pipe errors

# โ”€โ”€ Variables โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
NAME="Alice"          # no spaces around =
AGE=30
echo "Name: $NAME, Age: $AGE"
echo "Uppercase: ${NAME^^}"     # parameter expansion
echo "Default: ${UNDEF:-'N/A'}" # default if unset
RESULT=$(date +%Y)    # command substitution
SUM=$(( 5 + 3 ))      # arithmetic expansion

# โ”€โ”€ Arrays โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
FRUITS=("apple" "banana" "cherry")
echo "${FRUITS[0]}"    # first element: apple
echo "${FRUITS[@]}"    # all elements
echo "${#FRUITS[@]}"  # length: 3
FRUITS+=("date")      # append

# โ”€โ”€ Conditionals โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
if [[ "$NAME" == "Alice" ]]; then
    echo "Hello Alice!"
elif [[ "$NAME" == "Bob" ]]; then
    echo "Hello Bob!"
else
    echo "Who are you?"
fi

# Common test operators: [[ -f file ]] file exists
# [[ -d dir ]] directory exists | [[ -z "$var" ]] empty string
# [[ "$a" -gt "$b" ]] greater than | [[ "$a" == "$b" ]] equal
# [[ -r file ]] readable | [[ -w file ]] writable | [[ -x file ]] executable

# โ”€โ”€ Loops โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
for fruit in "${FRUITS[@]}"; do
    echo "I like $fruit"
done

for i in {1..5}; do         # brace expansion range
    echo "Count: $i"
done

for file in *.log; do        # iterate over files
    gzip "$file"
done

COUNT=0
while [[ "$COUNT" -lt 5 ]]; do
    echo "Count: $COUNT"
    (( COUNT++ ))
done

# โ”€โ”€ Functions โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
greet() {
    local name="$1"     # $1 = first argument, local = scoped
    echo "Hello, ${name:-World}!"
    return 0            # exit code (0 = success)
}
greet "Alice"          # call function
greet                   # uses default "World"

# โ”€โ”€ Script arguments โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# $0=script name, $1-$9=positional args, $@=all args
# $#=number of args, $?=last exit code, $$=PID

# โ”€โ”€ Error handling โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
cleanup() { echo "Cleaning up..."; }
trap cleanup EXIT      # run cleanup() on any exit
trap 'echo "Error on line $LINENO"' ERR

# โ”€โ”€ Logging helper โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
LOG_FILE="/var/log/myscript.log"
log() { echo "[$(date +%H:%M:%S)] $*" | tee -a "$LOG_FILE"; }
log "Script started"
โœ๏ธ
Vim Editor
The ubiquitous modal text editor โ€” available on every Linux system
MASTERY
๐Ÿ’ก
Vim has 4 main modes: NORMAL navigate/edit commands INSERT type text VISUAL select text COMMAND ex commands. Press Esc to always return to NORMAL mode. Start with vimtutor in your terminal!
NORMAL Navigation
h j k l โ€” โ† โ†“ โ†‘ โ†’ (character)
w / W โ€” next word start
b / B โ€” previous word start
e / E โ€” end of word
0 โ€” line start (col 0)
^ โ€” first non-whitespace
$ โ€” end of line
gg โ€” first line
G โ€” last line
:42 โ€” jump to line 42
Ctrl+d โ€” half page down
Ctrl+u โ€” half page up
% โ€” jump to matching bracket
* โ€” search word under cursor
INSERT Enter Insert Mode
i โ€” insert before cursor
I โ€” insert at line start
a โ€” append after cursor
A โ€” append at line end
o โ€” new line below, insert
O โ€” new line above, insert
s โ€” delete char and insert
S โ€” delete line and insert
C โ€” change to end of line
cc โ€” change whole line
Esc โ€” back to NORMAL mode
NORMAL Editing
x โ€” delete char at cursor
dd โ€” delete (cut) whole line
5dd โ€” delete 5 lines
dw โ€” delete word
d$ โ€” delete to line end
yy โ€” yank (copy) line
5yy โ€” yank 5 lines
yw โ€” yank word
p โ€” paste after cursor
P โ€” paste before cursor
u โ€” undo
Ctrl+r โ€” redo
. โ€” repeat last action
~ โ€” toggle case
COMMAND Ex Commands
:w โ€” save file
:q โ€” quit (fails if unsaved)
:wq or :x โ€” save and quit
:q! โ€” quit without saving
:w file.txt โ€” save as file.txt
:e file.txt โ€” open file
:vs file.txt โ€” vertical split
:sp file.txt โ€” horizontal split
Ctrl+w w โ€” switch split
:set nu โ€” show line numbers
:set nonu โ€” hide line numbers
:noh โ€” clear search highlight
:syntax on โ€” enable syntax hl
COMMAND Search & Replace
/pattern โ€” search forward
?pattern โ€” search backward
n โ€” next match
N โ€” previous match
:%s/old/new/g โ€” replace all
:%s/old/new/gc โ€” replace w/ confirm
:5,10s/old/new/g โ€” replace in lines 5-10
:g/pattern/d โ€” delete matching lines
:g/pattern/p โ€” print matching lines
VISUAL Selection
v โ€” character-wise visual
V โ€” line-wise visual
Ctrl+v โ€” block/column visual
Then: d=delete, y=yank, c=change
> / < โ€” indent / de-indent
~ โ€” toggle case of selection
U โ€” uppercase selection
u โ€” lowercase selection
: โ€” enter ex command for selection
With block: I insert before each line
๐Ÿ“ก
Linux Signals Reference
Inter-process communication through software signals
1SIGHUPHangup detected / reload config โ€” sent when terminal closes
2SIGINTInterrupt from keyboard (Ctrl+C)
3SIGQUITQuit from keyboard (Ctrl+\), produces core dump
9SIGKILLKill unconditionally โ€” cannot be caught or ignored
15SIGTERMTermination โ€” default kill signal, can be caught for cleanup
10SIGUSR1User-defined signal 1 โ€” app-specific (e.g. Nginx: reopen logs)
12SIGUSR2User-defined signal 2 โ€” app-specific
17SIGCHLDChild process stopped or terminated
18SIGCONTContinue if stopped (opposite of SIGSTOP)
19SIGSTOPStop process โ€” cannot be caught or ignored (Ctrl+Z sends 20)
Signal usage examplesbash
# Kill gracefully (SIGTERM โ€” gives process time to clean up)
kill -15 1234     # or: kill 1234

# Force kill (SIGKILL โ€” instant, no cleanup)
kill -9 1234      # or: kill -SIGKILL 1234

# Reload nginx config without downtime (SIGHUP)
sudo kill -HUP $(cat /var/run/nginx.pid)
# or: sudo nginx -s reload

# List all available signals
kill -l

# Trap signals in a bash script
trap 'echo "Caught SIGINT, cleaning up..."; cleanup; exit 1' SIGINT SIGTERM
๐Ÿง Linux Complete Cheatsheet  ยท  Use man [command] for full documentation  ยท  info [command] for detailed info pages
Everything is a file. Everything is a process. The shell is your canvas.