Linux Command Line
Updated: May 22, 2026Categories: Command Line, Linux
Printed from:
Linux Command Line Cheatsheet
Basic Navigation and File Operations
Directory and File Navigation
Bash
1234567891011121314151617# Print current working directory
pwd
# Change directory
cd /path/to/directory # Absolute path
cd .. # Go up one directory
cd ~ # Go to home directory
cd - # Go to previous directory
# List directory contents
ls # Basic listing
ls -l # Detailed list view
ls -a # Show hidden files
ls -lh # Human-readable file sizes
ls -lhS # Sort by size, largest first
ls --color=auto # Colorized output
File and Directory Management
Bash
123456789101112131415161718192021# Create directory
mkdir new_directory
mkdir -p /path/to/nested/directories # Create parent directories if they don't exist
# Remove directory
rmdir empty_directory # Only removes empty directories
rm -r directory # Recursively remove directory and its contents
rm -i file # Interactive (prompt before delete) — safer
# Copy files and directories
cp file1 destination/
cp -r directory destination/ # Recursive copy
cp -a source destination/ # Archive mode (preserves attributes, links, etc.)
# Move/Rename files and directories
mv oldname newname # Rename
mv file destination/ # Move file
# Create empty file or update timestamp
touch file.txt
File Permissions and Ownership
Chmod (Change Mode)
Bash
12345678910111213# Permission modes
chmod 755 file # rwxr-xr-x (Owner: read/write/execute, Group/Others: read/execute)
chmod u+x file # Add execute permission for user
chmod go-w file # Remove write permission for group and others
chmod -R 644 directory # Recursively set permissions
# Common permission values
# 4 = read, 2 = write, 1 = execute
# 7 (4+2+1): read, write, execute
# 6 (4+2): read, write
# 5 (4+1): read, execute
# 3 (2+1): write, execute
Ownership
Bash
123456789# Change file owner
chown user:group file
# Change group ownership
chgrp group file
# Recursively change ownership
chown -R user:group directory
Access Control Lists (ACLs)
Bash
1234getfacl file # View ACL
setfacl -m u:alice:rw file # Grant alice read/write
setfacl -x u:alice file # Remove alice's ACL entry
File Viewing and Editing
File Viewing
Bash
12345678910111213# View entire file
cat file.txt
# View file with pagination
less file.txt # Preferred (supports search with /)
more file.txt
# View first/last lines
head -n 10 file.txt # First 10 lines
tail -n 5 file.txt # Last 5 lines
tail -f logfile.log # Follow log file in real-time
tail -F logfile.log # Follow even if file is rotated
Text Editors
Bash
12345678910111213141516# Nano (beginner-friendly)
nano file.txt # Open/create file
# Shortcuts: Ctrl+X (exit), Ctrl+O (save)
# Vim (powerful, steep learning curve)
vim file.txt # Open/create file
# Modes:
# - Normal mode (Esc)
# - Insert mode (i)
# - Command mode (:)
# Commands:
# :w (save)
# :q (quit)
# :wq (save and quit)
# :q! (quit without saving)
File Searching and Pattern Matching
Find Files
Bash
1234567891011121314151617# Find by name
find /path -name "filename"
find . -type f -name "*.txt" # Find .txt files in current directory
find . -type f -iname "*.TXT" # Case-insensitive name match
# Find by size
find /path -size +10M # Files larger than 10MB
# Find by modification time
find /path -mtime -7 # Modified in last 7 days
# Execute command on results (safer with -exec ... +)
find . -name "*.log" -exec rm {} +
# Faster filesystem-wide search (requires updatedb)
locate filename
Grep (Search Text)
Bash
12345678910111213# Search in files
grep "pattern" file.txt
grep -r "pattern" directory/ # Recursive search
grep -R "pattern" directory/ # Recursive, follow symlinks
grep -i "pattern" file.txt # Case-insensitive
grep -n "pattern" file.txt # Show line numbers
grep -v "pattern" file.txt # Invert match
grep -E "(p1|p2)" file.txt # Extended regex (preferred over egrep)
grep -F "literal" file.txt # Fixed string (no regex)
# Faster code search (often pre-installed)
rg "pattern" # ripgrep — fast, respects .gitignore
Process Management
Process Listing
Bash
12345678910ps aux # List all processes (BSD style)
ps -ef # List all processes (System V style)
top # Real-time process viewer
htop # Interactive process viewer
btop # Modern interactive resource monitor
# Find specific process
pgrep -af process_name
ps aux | grep process_name
Process Control
Bash
123456789101112131415161718# Terminate processes
kill PID # Send SIGTERM (graceful)
kill -9 PID # Send SIGKILL (forceful)
killall process_name # Terminate all processes with name
pkill -f pattern # Kill by name/pattern
# Background/Foreground
bg # Send stopped job to background
fg # Bring background job to foreground
jobs # List background jobs
# Run process immune to hangup
nohup command &
# Run command in a persistent session (survives disconnect)
tmux # Modern terminal multiplexer
screen # Older terminal multiplexer
System Information
Bash
1234567891011121314151617uname -a # System information
hostnamectl # Hostname and OS details (systemd)
whoami # Current user
id # User and group IDs
uptime # System uptime
# Disk and Memory
df -h # Disk space usage
du -sh directory # Directory size
du -sh * | sort -h # Sort directories by size
free -h # Memory usage
lscpu # CPU information
lsblk # Block devices
lsmem # Memory ranges
lsusb # USB devices
lspci # PCI devices
Network Commands
Bash
1234567891011121314151617181920212223242526ping google.com # Test network connectivity
wget url # Download files
curl url # Transfer data
curl -O url # Save with remote filename
# SSH and File Transfer
ssh user@host # Remote login
ssh-keygen -t ed25519 # Generate modern SSH key pair
ssh-copy-id user@host # Install your public key on a remote host
scp file user@host:path # Secure copy (legacy; consider rsync/sftp)
rsync -avz source destination # Efficient file synchronization
rsync -avzP --delete src/ user@host:dst/ # Mirror with progress
# Network Statistics
ss -tuln # Socket statistics (replacement for netstat)
ss -tulpn # Include owning process
# Network Configuration (iproute2 replaces ifconfig/route)
ip addr # Show IP addresses
ip link # Show network interfaces
ip route # Show routing table
# DNS
dig example.com
host example.com
Archive and Compression
Bash
12345678910111213141516171819# Tar Archives
tar -cvf archive.tar files/ # Create tar archive
tar -xvf archive.tar # Extract tar archive
tar -czvf archive.tar.gz files/ # Create gzip-compressed archive
tar -xzvf archive.tar.gz # Extract gzip-compressed archive
tar -cJvf archive.tar.xz files/ # Create xz-compressed archive (better ratio)
# Gzip Compression
gzip file # Compress
gunzip file.gz # Decompress
# Zstandard (fast, modern compressor)
zstd file
unzstd file.zst
# Zip
zip -r archive.zip files/
unzip archive.zip
Text Processing
Bash
12345678910sort file.txt # Sort lines
sort -u file.txt # Sort and remove duplicates
uniq file.txt # Remove adjacent duplicate lines (sort first)
wc -l file.txt # Count lines
cut -d: -f1 file # Cut first field using : delimiter
tr 'A-Z' 'a-z' < file # Convert to lowercase
awk '{print $1}' file # Print first column
sed 's/old/new/g' file # Stream substitution
jq '.key' data.json # Parse and query JSON
Input/Output Redirection and Pipes
Bash
123456789101112# Redirection
command > output.txt # Overwrite stdout to file
command >> output.txt # Append stdout to file
command 2> err.txt # Redirect stderr
command &> all.txt # Redirect stdout and stderr (bash)
command < input.txt # Input from file
# Pipes
command1 | command2 # Output of command1 as input to command2
command | tee file.txt # Display and save output
command |& less # Pipe stdout and stderr (bash)
Environment Variables and Shell Configuration
Bash
123456789101112# View/Set Variables
echo $PATH
export VARNAME=value
printenv # List all environment variables
# Configuration Files
~/.bashrc # User-specific bash configuration
~/.bash_profile # Login shell configuration
~/.profile # POSIX login shell configuration
~/.zshrc # Zsh configuration (default shell on many systems)
/etc/environment # System-wide environment variables
Package Management
Debian/Ubuntu (apt)
Bash
12345678sudo apt update # Update package list
sudo apt upgrade # Upgrade packages
sudo apt install package # Install package
sudo apt remove package # Remove package
sudo apt autoremove # Remove unused dependencies
apt search keyword # Search packages
apt show package # Show package details
Red Hat/Fedora/CentOS Stream (dnf)
Bash
123456sudo dnf upgrade # Upgrade packages (replaces 'yum update')
sudo dnf install package # Install package
sudo dnf remove package # Remove package
sudo dnf search keyword # Search packages
# Note: 'yum' is deprecated on modern RHEL-family systems; use 'dnf'
Arch Linux (pacman)
Bash
1234sudo pacman -Syu # Sync and upgrade
sudo pacman -S package # Install package
sudo pacman -R package # Remove package
Universal Package Formats
Bash
1234567891011# Flatpak
flatpak install flathub app.id
flatpak run app.id
# Snap
sudo snap install package
snap list
# AppImage — just chmod +x and run
chmod +x app.AppImage && ./app.AppImage
Service Management
Bash
123456789101112# Systemd
sudo systemctl start service
sudo systemctl stop service
sudo systemctl restart service
sudo systemctl reload service
systemctl status service
sudo systemctl enable service # Start on boot
sudo systemctl enable --now service # Enable and start immediately
sudo systemctl disable service
systemctl list-units --type=service
systemctl --user start service # User-level service
Logs (journald)
Bash
1234567journalctl -xe # Recent logs with explanations
journalctl -u service_name # Logs for a specific service
journalctl -f # Follow logs in real-time
journalctl --since "1 hour ago"
journalctl -p err # Filter by priority (err, warning, info, etc.)
journalctl --vacuum-time=7d # Trim journal older than 7 days
Cron Jobs and Scheduling
Bash
12345678910# Edit crontab
crontab -e
crontab -l # List scheduled jobs
# Example: Run script every day at 2:30 AM
30 2 * * * /path/to/script.sh
# systemd timers (modern alternative to cron)
systemctl list-timers
User and Group Management
Bash
1234567891011# User Management
sudo useradd -m username
sudo usermod -aG groupname username
sudo userdel -r username
sudo passwd username
# Switch Users
su - username # Switch user
sudo command # Run command with elevated privileges
sudo -i # Start a root login shell
Troubleshooting Commands
Bash
123456789dmesg # Kernel messages
dmesg -T # With human-readable timestamps
journalctl -xe # System logs
strace -p PID # Trace system calls of a running process
ltrace command # Trace library calls
lsof -i :PORT # Find process using a port
lsof -p PID # List files opened by a process
watch -n 2 command # Re-run command every 2 seconds
Useful Shortcuts
Bash
1234567891011Ctrl+C # Terminate current process
Ctrl+Z # Suspend current process
Ctrl+D # Send EOF / log out of shell
Ctrl+R # Reverse history search
Ctrl+L # Clear the screen
Ctrl+A / Ctrl+E # Jump to start / end of line
Ctrl+U / Ctrl+K # Cut from cursor to start / end of line
!! # Repeat last command
!$ # Last argument of previous command
sudo !! # Re-run last command with sudo
Shell Scripting Basics
Bash
1234567891011121314151617181920212223242526#!/usr/bin/env bash # Portable shebang
set -euo pipefail # Safer defaults: exit on error, undefined vars, pipe failures
variable="value" # Variable assignment (no spaces around =)
echo "$variable" # Always quote variables
# Conditional
if [[ -f "$file" ]]; then
echo "File exists"
fi
# Loops
for f in *.txt; do
echo "$f"
done
# Functions
greet() {
local name="$1"
echo "Hello, $name"
}
greet "world"
# Command substitution (prefer $() over backticks)
today=$(date +%F)
Modern CLI Alternatives
Bash
1234567891011# Often-recommended replacements
bat # 'cat' with syntax highlighting
eza # Modern 'ls' replacement (successor to exa)
fd # Friendlier 'find'
rg # Fast 'grep' (ripgrep)
dust # Visual 'du'
duf # Visual 'df'
btop # Modern 'top'/'htop'
fzf # Fuzzy finder for files, history, etc.
zoxide # Smarter 'cd' that learns your habits
Pro Tips
- Always use
man command(ortldr commandfor quick examples) for documentation - Use
--helpfor a quick option summary on most tools - Test destructive commands with
echoor--dry-runfirst - Quote variable expansions (
"$var") to avoid word-splitting bugs - Prefer
set -euo pipefailin scripts for safer error handling - Use
tmuxorscreenfor long-running remote sessions - Practice regularly to build muscle memory
Disclaimer: Always be careful with commands that modify system files or have destructive potential. Double-check rm -rf, redirection (>), and any command run as root.
Continue Learning
Discover more cheatsheets to boost your productivity