Linux Command Cheatsheet

File Operations

Navigation and Listing

# Navigation
cd /path/to/dir              # Change directory
cd -                         # Previous directory
cd ~                         # Home directory
pwd                          # Print working directory

# Listing
ls -la                       # List all with details
ls -lah                      # Human-readable sizes
ls -lt                       # Sort by modification time
ls -lS                       # Sort by size
ls -R                        # Recursive listing
tree -L 2                    # Tree view, 2 levels deep

File Management

# Copy
cp file dest                 # Copy file
cp -r dir/ dest/             # Copy directory recursively
cp -a dir/ dest/             # Archive mode (preserve all)
cp -n file dest              # Don't overwrite existing

# Move/Rename
mv file dest                 # Move or rename
mv -n file dest              # Don't overwrite
mv -i file dest              # Interactive (prompt)

# Delete
rm file                      # Remove file
rm -r dir/                   # Remove directory
rm -rf dir/                  # Force remove (DANGER)
rmdir dir/                   # Remove empty directory

# Create
touch file                   # Create empty file
mkdir dir                    # Create directory
mkdir -p a/b/c               # Create nested directories

File Content

# View
cat file                     # Print entire file
less file                    # Paginated view
head -n 20 file              # First 20 lines
tail -n 20 file              # Last 20 lines
tail -f file                 # Follow (live updates)

# Search
grep pattern file            # Search in file
grep -r pattern dir/         # Recursive search
grep -i pattern file         # Case insensitive
grep -v pattern file         # Invert match
grep -n pattern file         # Show line numbers
grep -c pattern file         # Count matches
grep -l pattern *.txt        # List matching files only

# Find files
find . -name "*.txt"                  # By name
find . -type f -size +100M            # Files > 100MB
find . -type f -mtime -7              # Modified last 7 days
find . -type f -exec chmod 644 {} \;  # Execute command
locate filename                        # Fast search (updatedb)

Permissions

# Change permissions
chmod 755 file               # rwxr-xr-x
chmod 644 file               # rw-r--r--
chmod +x file                # Add execute
chmod -w file                # Remove write
chmod -R 755 dir/            # Recursive

# Change ownership
chown user:group file        # Change owner and group
chown -R user:group dir/     # Recursive
chgrp group file             # Change group only

# Permission reference
# r=4, w=2, x=1
# 755 = rwxr-xr-x (owner:rwx, group:rx, other:rx)
# 644 = rw-r--r-- (owner:rw, group:r, other:r)
# 700 = rwx------ (owner only)
# Symbolic links
ln -s target linkname        # Create symlink
ln -sf target linkname       # Force create (overwrite)
readlink -f linkname         # Resolve symlink

# Hard links
ln target linkname           # Create hard link

Text Processing

sed (Stream Editor)

# Substitution
sed 's/old/new/' file              # First occurrence per line
sed 's/old/new/g' file             # All occurrences
sed -i 's/old/new/g' file          # Edit in place
sed -i.bak 's/old/new/g' file      # Edit with backup

# Delete
sed '/pattern/d' file              # Delete matching lines
sed '5d' file                      # Delete line 5
sed '5,10d' file                   # Delete lines 5-10

# Print
sed -n '5p' file                   # Print line 5
sed -n '5,10p' file                # Print lines 5-10
sed -n '/pattern/p' file           # Print matching lines

# Insert/Append
sed '3i\new line' file             # Insert before line 3
sed '3a\new line' file             # Append after line 3

awk

# Field extraction
awk '{print $1}' file              # First column
awk '{print $1, $3}' file          # Columns 1 and 3
awk -F: '{print $1}' /etc/passwd   # Custom delimiter

# Patterns
awk '/pattern/' file               # Print matching lines
awk '$3 > 100' file                # Conditional
awk 'NR==5' file                   # Line 5 only
awk 'NR>=5 && NR<=10' file         # Lines 5-10

# Calculations
awk '{sum+=$1} END {print sum}' file     # Sum column 1
awk '{sum+=$1} END {print sum/NR}' file  # Average

# Variables
awk -v var="value" '{print var, $1}' file

sort, uniq, cut

# Sort
sort file                    # Alphabetical
sort -n file                 # Numeric
sort -r file                 # Reverse
sort -k2 file                # By column 2
sort -t: -k3 -n /etc/passwd  # By field with delimiter
sort -u file                 # Unique only

# Unique
uniq file                    # Remove adjacent duplicates
uniq -c file                 # Count occurrences
uniq -d file                 # Show only duplicates
sort file | uniq             # Remove all duplicates

# Cut
cut -d: -f1 /etc/passwd      # Extract field 1
cut -c1-10 file              # Characters 1-10
cut -d, -f2,4 file.csv       # Fields 2 and 4

Other Text Tools

# Word/line counts
wc -l file                   # Line count
wc -w file                   # Word count
wc -c file                   # Byte count

# Diff and patch
diff file1 file2             # Compare files
diff -u file1 file2          # Unified format
diff -r dir1/ dir2/          # Compare directories
patch < changes.patch        # Apply patch

# Translate/delete
tr 'a-z' 'A-Z' < file        # Lowercase to uppercase
tr -d '\r' < file            # Remove carriage returns
tr -s ' ' < file             # Squeeze repeated spaces

# Column formatting
column -t file               # Tabulate
paste file1 file2            # Merge files side by side
join file1 file2             # Join on common field

System Information

Hardware

# CPU
lscpu                        # CPU architecture info
cat /proc/cpuinfo            # Detailed CPU info
nproc                        # Number of processors

# Memory
free -h                      # Memory usage
cat /proc/meminfo            # Detailed memory info
vmstat 1                     # Virtual memory stats

# Storage
lsblk                        # Block devices
lsblk -f                     # With filesystem info
df -h                        # Disk space usage
du -sh dir/                  # Directory size
du -h --max-depth=1          # Sizes one level deep
fdisk -l                     # Partition tables

# PCI/USB
lspci                        # PCI devices
lspci -v                     # Verbose
lsusb                        # USB devices
lsusb -v                     # Verbose

# General
uname -a                     # Kernel and system info
hostnamectl                  # Hostname and OS info
dmidecode                    # DMI/SMBIOS info (root)

Network

# Interfaces
ip addr                      # IP addresses
ip link                      # Interface status
ip route                     # Routing table
ip neigh                     # ARP cache

# Connections
ss -tlnp                     # Listening TCP ports
ss -ulnp                     # Listening UDP ports
ss -tn                       # Established TCP
ss -s                        # Socket statistics

# DNS
dig example.com              # DNS lookup
dig @8.8.8.8 example.com     # Specific DNS server
host example.com             # Simple lookup
nslookup example.com         # Interactive lookup
cat /etc/resolv.conf         # DNS configuration

# Connectivity
ping -c 3 host               # ICMP test
traceroute host              # Path trace
mtr host                     # Combined ping/traceroute
curl -I https://example.com  # HTTP headers
wget -O - URL                # Download to stdout
nc -zv host port             # Port test

Process Management

Viewing Processes

# Process listing
ps aux                       # All processes
ps -ef                       # Full format
ps -u username               # User's processes
ps --forest                  # Process tree
pstree                       # Tree view

# Real-time monitoring
top                          # Interactive process viewer
htop                         # Enhanced top (if installed)
atop                         # Advanced system monitor

# Process info
pidof program                # Get PID
pgrep -a pattern             # Search processes
lsof -p PID                  # Files opened by process
lsof -i :port                # Process using port

Controlling Processes

# Signals
kill PID                     # SIGTERM (graceful)
kill -9 PID                  # SIGKILL (force)
kill -HUP PID                # SIGHUP (reload)
killall program              # Kill by name
pkill pattern                # Kill by pattern

# Background/Foreground
command &                    # Run in background
jobs                         # List background jobs
fg %1                        # Bring job 1 to foreground
bg %1                        # Continue job 1 in background
Ctrl+Z                       # Suspend current process
nohup command &              # Run immune to hangups
disown %1                    # Detach job from shell

# Priority
nice -n 10 command           # Run with lower priority
renice -n 10 -p PID          # Change running process priority

User Management

User Operations

# Current user
whoami                       # Current username
id                           # User and group IDs
groups                       # Group memberships

# User management
useradd username             # Create user
useradd -m -s /bin/bash user # With home dir and shell
userdel username             # Delete user
userdel -r username          # Delete with home directory
usermod -aG group user       # Add to group
usermod -s /bin/zsh user     # Change shell

# Password
passwd                       # Change own password
passwd username              # Change user's password (root)
chage -l username            # Password aging info

Group Operations

groupadd groupname           # Create group
groupdel groupname           # Delete group
gpasswd -a user group        # Add user to group
gpasswd -d user group        # Remove user from group
newgrp groupname             # Switch primary group

Switching Users

su - username                # Switch user (login shell)
su username                  # Switch user (no login shell)
sudo command                 # Run as root
sudo -u user command         # Run as specific user
sudo -i                      # Root login shell
sudo -s                      # Root shell

Package Management

Arch Linux (pacman)

# Update
pacman -Sy                   # Sync package database
pacman -Syu                  # Full system upgrade

# Install/Remove
pacman -S package            # Install package
pacman -Rs package           # Remove with dependencies
pacman -Rns package          # Remove with deps and configs

# Search/Info
pacman -Ss keyword           # Search packages
pacman -Si package           # Package info (remote)
pacman -Qi package           # Package info (local)
pacman -Ql package           # List package files
pacman -Qo /path/to/file     # Which package owns file

# Cleanup
pacman -Sc                   # Clean package cache
pacman -Qdt                  # List orphaned packages
pacman -Rns $(pacman -Qdtq)  # Remove orphans

Debian/Ubuntu (apt)

# Update
apt update                   # Update package lists
apt upgrade                  # Upgrade packages
apt full-upgrade             # Full upgrade

# Install/Remove
apt install package          # Install
apt remove package           # Remove
apt purge package            # Remove with configs
apt autoremove               # Remove unused deps

# Search/Info
apt search keyword           # Search
apt show package             # Package info
apt list --installed         # List installed
dpkg -L package              # List package files
dpkg -S /path/to/file        # Which package owns file

RHEL/Fedora (dnf)

# Update
dnf check-update             # Check for updates
dnf upgrade                  # Upgrade packages

# Install/Remove
dnf install package          # Install
dnf remove package           # Remove
dnf autoremove               # Remove unused deps

# Search/Info
dnf search keyword           # Search
dnf info package             # Package info
dnf list installed           # List installed
rpm -ql package              # List package files
rpm -qf /path/to/file        # Which package owns file

Systemd

Service Management

# Status
systemctl status service     # Service status
systemctl is-active service  # Quick active check
systemctl is-enabled service # Check if enabled

# Control
systemctl start service      # Start service
systemctl stop service       # Stop service
systemctl restart service    # Restart service
systemctl reload service     # Reload configuration
systemctl enable service     # Enable at boot
systemctl disable service    # Disable at boot
systemctl enable --now svc   # Enable and start

# Listing
systemctl list-units         # All active units
systemctl list-units --all   # All units
systemctl list-unit-files    # Unit files
systemctl --failed           # Failed units

Journalctl

# View logs
journalctl                   # All logs
journalctl -f                # Follow (live)
journalctl -u service        # Service logs
journalctl -b                # Current boot
journalctl -b -1             # Previous boot
journalctl --since "1 hour ago"
journalctl --since "2024-01-01" --until "2024-01-02"

# Filtering
journalctl -p err            # Priority: emerg, alert, crit, err, warning, notice, info, debug
journalctl -k                # Kernel messages
journalctl _UID=1000         # By user ID

# Management
journalctl --disk-usage      # Journal size
journalctl --vacuum-size=1G  # Limit to 1GB
journalctl --vacuum-time=1w  # Keep 1 week

Disk and Storage

Disk Operations

# Partitioning
fdisk /dev/sdX               # MBR partitioning
gdisk /dev/sdX               # GPT partitioning
parted /dev/sdX              # Parted (MBR/GPT)
cfdisk /dev/sdX              # Curses interface

# Filesystem
mkfs.ext4 /dev/sdX1          # Create ext4
mkfs.xfs /dev/sdX1           # Create XFS
mkfs.btrfs /dev/sdX1         # Create Btrfs
mkswap /dev/sdX2             # Create swap

# Mount
mount /dev/sdX1 /mnt         # Mount filesystem
mount -t nfs server:/path /mnt  # Mount NFS
umount /mnt                  # Unmount
mount -o remount,rw /        # Remount with options
findmnt                      # Show mount tree

# Filesystem check
fsck /dev/sdX1               # Check filesystem (unmounted!)
fsck -y /dev/sdX1            # Auto-fix
e2fsck -f /dev/sdX1          # Force ext check
xfs_repair /dev/sdX1         # XFS repair

LVM

# Physical volumes
pvcreate /dev/sdX1           # Create PV
pvs                          # List PVs
pvdisplay                    # PV details

# Volume groups
vgcreate vg0 /dev/sdX1       # Create VG
vgextend vg0 /dev/sdY1       # Add PV to VG
vgs                          # List VGs
vgdisplay                    # VG details

# Logical volumes
lvcreate -L 10G -n lv0 vg0   # Create 10GB LV
lvcreate -l 100%FREE -n lv0 vg0  # Use all free space
lvextend -L +5G /dev/vg0/lv0 # Extend by 5GB
lvextend -l +100%FREE /dev/vg0/lv0  # Use remaining
lvs                          # List LVs
lvdisplay                    # LV details

# Resize filesystem after lvextend
resize2fs /dev/vg0/lv0       # ext3/4
xfs_growfs /mnt              # XFS (mounted)

Compression and Archives

tar

# Create archives
tar cvf archive.tar files/         # Create tar
tar czvf archive.tar.gz files/     # Gzip compressed
tar cjvf archive.tar.bz2 files/    # Bzip2 compressed
tar cJvf archive.tar.xz files/     # XZ compressed

# Extract
tar xvf archive.tar                # Extract tar
tar xzvf archive.tar.gz            # Extract gzip
tar xjvf archive.tar.bz2           # Extract bzip2
tar xJvf archive.tar.xz            # Extract xz
tar xvf archive.tar -C /dest/      # Extract to directory

# List contents
tar tvf archive.tar                # List contents

# Add/Update
tar rvf archive.tar newfile        # Add file
tar uvf archive.tar files/         # Update changed files

Other Compression

# Gzip
gzip file                    # Compress (replaces original)
gzip -k file                 # Keep original
gunzip file.gz               # Decompress
zcat file.gz                 # View without extracting

# Bzip2
bzip2 file                   # Compress
bunzip2 file.bz2             # Decompress
bzcat file.bz2               # View

# XZ
xz file                      # Compress
unxz file.xz                 # Decompress
xzcat file.xz                # View

# Zip
zip archive.zip files        # Create zip
zip -r archive.zip dir/      # Recursive
unzip archive.zip            # Extract
unzip -l archive.zip         # List contents

SSH and Remote

SSH Operations

# Connect
ssh user@host                # Basic connection
ssh -p 2222 user@host        # Custom port
ssh -i key.pem user@host     # Specific key

# Key management
ssh-keygen -t ed25519        # Generate Ed25519 key
ssh-keygen -t rsa -b 4096    # Generate RSA key
ssh-copy-id user@host        # Copy public key to server

# SSH agent
eval $(ssh-agent)            # Start agent
ssh-add ~/.ssh/key           # Add key to agent
ssh-add -l                   # List keys in agent

# Tunneling
ssh -L 8080:localhost:80 user@host    # Local forward
ssh -R 8080:localhost:80 user@host    # Remote forward
ssh -D 1080 user@host                 # SOCKS proxy

File Transfer

# SCP
scp file user@host:/path/    # Copy to remote
scp user@host:/path/file .   # Copy from remote
scp -r dir user@host:/path/  # Recursive

# Rsync
rsync -av src/ dest/         # Archive mode
rsync -av src/ user@host:/path/    # To remote
rsync -av user@host:/path/ dest/   # From remote
rsync -avz --progress src/ dest/   # Compressed + progress
rsync -av --delete src/ dest/      # Mirror (delete extras)
rsync -av --exclude='*.log' src/ dest/  # Exclude pattern

Cron and Scheduling

Crontab

# Manage crontab
crontab -e                   # Edit user crontab
crontab -l                   # List crontab
crontab -r                   # Remove crontab
crontab -u user -e           # Edit other user's crontab

# Cron format
# m h dom mon dow command
# * * * * * command          # Every minute
# 0 * * * * command          # Every hour
# 0 0 * * * command          # Daily at midnight
# 0 0 * * 0 command          # Weekly (Sunday)
# 0 0 1 * * command          # Monthly

# Examples
0 5 * * * /path/to/script    # Daily at 5:00 AM
*/15 * * * * command         # Every 15 minutes
0 9-17 * * 1-5 command       # Weekdays 9am-5pm hourly

Systemd Timers

# List timers
systemctl list-timers        # Active timers
systemctl list-timers --all  # All timers

# Timer control
systemctl enable timer.timer
systemctl start timer.timer
systemctl status timer.timer

Miscellaneous

Date and Time

date                         # Current date/time
date +%Y-%m-%d               # Format: 2024-01-15
date +%Y%m%d-%H%M%S          # Timestamp
date -d "yesterday"          # Relative date
date -d "+1 week"            # Future date

timedatectl                  # Time status
timedatectl set-timezone TZ  # Set timezone
timedatectl set-ntp true     # Enable NTP

Environment

env                          # All environment vars
echo $VARIABLE               # Print variable
export VAR=value             # Set for session
unset VAR                    # Unset variable

# Permanent (add to ~/.bashrc or ~/.zshrc)
export PATH="$PATH:/new/path"

History

history                      # Command history
history 20                   # Last 20 commands
!n                           # Run command n
!!                           # Repeat last command
!string                      # Last command starting with string
Ctrl+r                       # Reverse search

Aliases

alias                        # List aliases
alias ll='ls -la'            # Create alias
unalias ll                   # Remove alias

# Common useful aliases (add to ~/.bashrc)
alias ll='ls -la'
alias la='ls -A'
alias ..='cd ..'
alias ...='cd ../..'
alias grep='grep --color=auto'

Quick Reference Table

Task Command Notes

Find files

find . -name "*.txt"

By name pattern

Search in files

grep -r "pattern" dir/

Recursive search

Disk usage

df -h / du -sh dir/

Filesystem / Directory

Memory usage

free -h

Human-readable

Running processes

ps aux / top / htop

Snapshot / Real-time

Network connections

ss -tlnp

Listening TCP + process

Service status

systemctl status svc

Systemd service

View logs

journalctl -u svc -f

Follow service logs

File permissions

chmod 755 file

rwxr-xr-x

Ownership

chown user:group file

Change owner

Compress

tar czvf file.tar.gz dir/

Gzip tar archive

Extract

tar xzvf file.tar.gz

Extract tar.gz

SSH connect

ssh user@host

Remote shell

Copy remote

scp file user@host:/path

Secure copy