Linux Command Cheat Sheet

Comprehensive Linux command reference covering navigation, files, text processing, permissions, processes, system information, networking, archives, services, storage, and troubleshooting.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Files and Directories
Create file or update timestamp
touch notes.txt

# Create an empty file if it does not exist.

Create nested directories
mkdir -p app/logs/archive

# Create one or more directories, including parents.

Copy files recursively
cp -av src/ backup/src/

# Copy files or directories.

Move or rename file
mv old-name.txt new-name.txt

# Move or rename a file or directory.

Remove file
rm file.txt

# Delete a file.

Remove directory recursively
rm -rf build/

# Delete a directory tree forcefully.

Remove empty directory
rmdir empty-dir

# Delete an empty directory.

Create symbolic link
ln -s /opt/app/current app-current

# Create a symlink that points to another path.

Create hard link
ln original.txt twin.txt

# Create an additional directory entry for the same inode.

Show file metadata
stat /var/log/syslog

# Display inode, permissions, timestamps, and size.

Detect file type
file archive.tar.gz

# Identify file contents and encoding.

Show disk usage by path
du -sh *

# Estimate file and directory sizes.

Show filesystem free space
df -h

# Display mounted filesystems and free space.

Strip directory and suffix from path
basename /var/log/nginx/access.log .log

# Return the last path component.

Get directory portion of path
dirname /var/log/nginx/access.log

# Return the parent directory of a path.

## Viewing and Text Basics
Print file contents
cat /etc/os-release

# Concatenate and print files to standard output.

Page through a file
less /var/log/syslog

# Open a file in a scrollable pager.

Show last lines
tail -n 50 app.log

# Display the end of a file.

Follow a growing file
tail -f /var/log/nginx/access.log

# Stream appended lines as they are written.

Count lines words and bytes
wc -l users.csv

# Count content in files or streams.

Number lines
nl -ba config.yml

# Display file contents with line numbers.

Select fields from lines
cut -d: -f1 /etc/passwd

# Extract portions of each line.

Merge lines side-by-side
paste names.txt emails.txt

# Combine files line-by-line.

Pretty-print columns
column -t -s, data.csv

# Format delimited text into aligned columns.

Sort lines
sort -t, -k2,2n scores.csv

# Sort input lines lexicographically or numerically.

Filter duplicate adjacent lines
sort access.log | uniq -c | sort -nr

# Collapse repeated adjacent lines.

Translate or delete characters
tr '[:lower:]' '[:upper:]' < input.txt

# Replace or delete characters from a stream.

Write output to file and stdout
make 2>&1 | tee build.log

# Send output to both a file and the terminal.

## Searching and Pattern Matching
Search text with grep
grep -n 'ERROR' app.log

# Print lines matching a pattern.

Search recursively under a directory
grep -RIn 'TODO' src/

# Search all matching files in a tree.

Show non-matching lines
grep -v '^#' .env.example

# Exclude lines that match a pattern.

Extended regex search
grep -E 'warn|error|fatal' app.log

# Use extended regular expressions with grep.

Fixed-string search
grep -F 'user[id]' app.log

# Match text literally instead of as a regex.

Fast recursive search with rg
rg 'connection refused' .

# Recursively search text quickly while respecting ignore rules.

Find files by modification time
find /var/log -type f -mtime -1

# Search for files changed recently.

Find files by size
find / -type f -size +500M 2>/dev/null

# Locate large files with size filters.

Build command lines from stdin
find . -name '*.tmp' -print0 | xargs -0 rm -f

# Pass stdin items as arguments to another command.

Search shell history
history | grep docker

# Filter previous shell commands.

## Permissions Ownership and ACLs
List permissions
ls -l /var/www

# Show permissions and ownership on files.

Change permissions with numeric mode
chmod 640 secrets.env

# Set rwx permissions numerically.

Change permissions recursively
chmod -R u=rwX,go=rX public/

# Apply a mode to a directory tree.

Change owner and group
chown deploy:www-data app.log

# Set file owner and group.

Change group owner
chgrp www-data storage/

# Set the group of a file or directory.

Show or set default permission mask
umask 027

# Control default modes for new files and directories.

Show current user and groups
id

# Display numeric and named identity info.

Print current username
whoami

# Show the effective user name.

Show ACLs
getfacl shared/

# Inspect Access Control Lists on a file or directory.

Set ACL entries
setfacl -m u:alice:rwx shared/

# Grant or modify fine-grained access rules.

Run command as root
sudo systemctl restart nginx

# Execute a command with elevated privileges.

Edit protected file safely
sudoedit /etc/ssh/sshd_config

# Open a file for editing through sudo.

## Users Groups and Sessions
Create a user
sudo useradd -m -s /bin/bash deploy

# Create a new local user account.

Add user to supplementary group
sudo usermod -aG docker alice

# Append a user to an extra group.

Set or change password
sudo passwd deploy

# Set a local user password.

Create a group
sudo groupadd appteam

# Add a new local group.

List groups for a user
groups alice

# Show supplementary group membership.

Switch user with login shell
su - postgres

# Become another user and load their shell profile.

Show logged in users
who

# List active login sessions.

Show logged in users and activity
w

# Display users plus current processes and load.

Show login history
last -a | head

# Display recent login records.

Kill all processes for a user
sudo pkill -u olddeploy

# Terminate processes owned by a specific user.

## Processes Jobs and Scheduling
List processes
ps aux

# Show running processes in BSD format.

Show process tree
ps -ef --forest

# Display processes in a parent-child tree.

Interactive process viewer
top

# Monitor processes, CPU, and memory interactively.

Interactive process viewer with UI
htop

# Use a richer interactive process monitor.

Find process IDs by name
pgrep -af nginx

# Search for process IDs using a pattern.

Send TERM signal
kill -TERM 12345

# Request graceful process termination.

Force kill process
kill -KILL 12345

# Send SIGKILL to stop a process immediately.

Kill processes by pattern
pkill -f 'gunicorn: master'

# Signal processes matching a name or regex.

Start process with adjusted priority
nice -n 10 tar -czf backup.tgz /srv/data

# Run a command at a different CPU scheduling priority.

Change running process priority
sudo renice -n 5 -p 12345

# Adjust niceness of an existing process.

List shell jobs
jobs -l

# Show background and stopped jobs for the current shell.

Resume stopped job in background
bg %1

# Continue a suspended job in the background.

Bring job to foreground
fg %1

# Resume a background or stopped job in the foreground.

Keep process running after logout
nohup ./long-task.sh > task.out 2>&1 &

# Run a command immune to hangups.

Edit user crontab
crontab -e

# Create or modify scheduled tasks.

List user crontab
crontab -l

# Show scheduled cron entries.

Schedule one-time job
echo 'systemctl restart worker' | at 02:00

# Queue a command to run once later.

## System Information and Hardware
Show kernel and system info
uname -a

# Print kernel and architecture details.

Show or set hostname
hostnamectl

# Inspect hostname, OS, and virtualization metadata.

Show distribution info
cat /etc/os-release

# Print distribution metadata from os-release.

Show uptime and load
uptime

# Print system uptime and load averages.

Show memory usage
free -h

# Display RAM and swap usage.

Show CPU information
lscpu

# Display CPU architecture and core details.

List block devices
lsblk -f

# Show disks, partitions, and mountpoints.

Show block device UUIDs
sudo blkid

# Display filesystem type and UUID labels.

Show or mount filesystems
mount | column -t

# List mounted filesystems or mount one manually.

Unmount a filesystem
sudo umount /mnt/data

# Detach a mounted filesystem.

Show kernel ring buffer
dmesg -T | tail -n 50

# Inspect kernel messages and boot-time hardware logs.

List USB devices
lsusb

# Display connected USB hardware.

List PCI devices
lspci -nn

# Display PCI and PCIe hardware.

## Networking and Remote Access
Show IP addresses
ip address show

# Display interfaces and assigned addresses.

Show routing table
ip route show

# Display current IP routes.

List listening sockets
ss -tulpn

# Show listening TCP and UDP ports with processes.

Test basic reachability
ping -c 4 8.8.8.8

# Send ICMP echo requests to a host.

Trace network path
traceroute example.com

# Display the route packets take to a host.

Query DNS records
dig +short A example.com

# Look up DNS answers directly.

Basic DNS lookup
nslookup example.com

# Query DNS information interactively or directly.

Simple DNS lookup
host 8.8.8.8

# Resolve names or reverse-lookup addresses.

Transfer data with URLs
curl -I https://example.com

# Make HTTP requests and API calls.

Download files over HTTP FTP
wget https://example.com/file.tar.gz

# Retrieve files non-interactively.

Open remote shell
ssh user@server.example.com

# Connect securely to another host.

Copy files over SSH
scp app.tar.gz user@server:/tmp/

# Transfer files between hosts securely.

Synchronize files over SSH
rsync -avz ./dist/ user@server:/var/www/app/

# Copy files efficiently with deltas and preservation.

Open TCP or UDP connections
nc -vz example.com 443

# Use netcat for port checks and simple listeners.

Scan ports and services
nmap -sV example.com

# Probe a host for open ports and services.

Capture packets
sudo tcpdump -i any port 443

# Inspect network traffic from the command line.

## Archives Compression and Checksums
Create tar archive
tar -cvf backup.tar app/

# Bundle files into a tar archive.

Create gzip-compressed tarball
tar -czvf backup.tar.gz app/

# Archive and compress in one step.

Extract tarball
tar -xzvf backup.tar.gz

# Unpack an archive into the current directory.

Compress file with gzip
gzip large.log

# Compress a file and replace it with a `.gz` version.

Decompress gzip file
gunzip large.log.gz

# Expand a `.gz` file back to its original contents.

Create zip archive
zip -r release.zip dist/

# Archive and compress files in zip format.

Extract zip archive
unzip release.zip -d release/

# Unpack zip files.

Compress with xz
xz -T0 dump.sql

# Compress a file using xz.

Generate SHA-256 checksum
sha256sum release.tar.gz

# Compute file integrity digest.

Generate MD5 checksum
md5sum file.iso

# Compute MD5 digest.

## sed awk and Structured Text Workflows
Replace text with sed
sed 's/localhost/db.internal/g' config.tpl

# Substitute matching text in a stream.

Edit file in place with sed
sed -i.bak 's/debug=false/debug=true/' app.conf

# Modify a file directly.

Print line range
sed -n '100,140p' big.log

# Show a line range from a file.

Print selected columns with awk
awk '{print $1, $5}' access.log

# Extract columns from whitespace-delimited text.

Sum values with awk
awk '{sum += $3} END {print sum}' metrics.txt

# Aggregate numeric values from a column.

Filter rows with awk
awk '$5 > 100 {print $0}' usage.txt

# Print rows that satisfy a condition.

Pretty-print JSON
jq '.' response.json

# Format JSON output for readability.

Extract JSON field
jq -r '.items[].metadata.name' pods.json

# Read a nested field from JSON.

Read YAML field
yq '.services.web.image' docker-compose.yml

# Extract data from YAML.

Compare sorted files line-by-line
comm -3 <(sort old.txt) <(sort new.txt)

# Show lines unique to each file or common to both.

Join two files on a common field
join -1 1 -2 1 users.txt emails.txt

# Relational join for sorted text files.

Split file into chunks
split -l 100000 huge.csv chunk_

# Break a file into smaller pieces.

## Services systemd and Journal
Show service status
systemctl status nginx

# Display service state and recent log snippets.

Start service
sudo systemctl start nginx

# Start a service immediately.

Stop service
sudo systemctl stop nginx

# Stop a running service.

Restart service
sudo systemctl restart nginx

# Restart a service cleanly.

Reload service config
sudo systemctl reload nginx

# Ask a service to reload configuration without full restart.

Enable service on boot
sudo systemctl enable nginx

# Create boot-time activation links for a unit.

Disable service on boot
sudo systemctl disable nginx

# Remove boot-time activation for a unit.

List loaded units
systemctl list-units --type=service

# Show active units known to systemd.

View logs for a service
journalctl -u nginx -n 100 --no-pager

# Show journal entries for a specific systemd unit.

Follow journal logs
journalctl -fu nginx

# Stream new journal entries live.

Show logs from current boot
journalctl -b

# Query logs for the active boot session.

Inspect time and timezone settings
timedatectl

# Show or change system clock, timezone, and NTP status.

Set hostname with systemd
sudo hostnamectl set-hostname app-prod-01

# Change the system hostname.

## Storage Partitions and LVM
List partition tables
sudo fdisk -l

# Show partitions on available disks.

Print partition layout
sudo parted /dev/sda print

# Inspect partitions with GNU Parted.

Create ext4 filesystem
sudo mkfs.ext4 /dev/sdb1

# Format a block device with ext4.

Check filesystem
sudo fsck -f /dev/sdb1

# Check and repair a filesystem.

Mount device to path
sudo mount /dev/sdb1 /mnt/data

# Attach a filesystem to a mountpoint.

Enable swap device or file
sudo swapon /swapfile

# Activate swap space.

Disable swap device or file
sudo swapoff /swapfile

# Turn off swap usage.

List physical volumes
sudo pvs

# Show LVM physical volumes.

List volume groups
sudo vgs

# Show LVM volume groups.

List logical volumes
sudo lvs

# Show LVM logical volumes.

Extend logical volume
sudo lvextend -L +20G /dev/vg0/data

# Increase logical volume size.

Grow ext filesystem
sudo resize2fs /dev/vg0/data

# Resize an ext2/3/4 filesystem after volume growth.

## Performance Monitoring and Troubleshooting
Show virtual memory stats
vmstat 1 5

# Display system activity, processes, memory, and IO over time.

Show CPU and disk IO stats
iostat -xz 1 5

# Report CPU utilization and block-device performance.

Collect and report system activity
sar -u 1 5

# Use sysstat historical metrics.

Show per-CPU stats
mpstat -P ALL 1 5

# Display CPU usage by processor.

Show per-process stats
pidstat 1 5

# Report CPU, memory, and IO by process.

List open files
lsof -i :8080

# Show files and sockets opened by processes.

Trace system calls
strace -p 12345

# Inspect syscalls made by a process or command.

Measure command runtime
time rsync -av src/ backup/

# Report elapsed user and system time for a command.

Run a command repeatedly
watch -n 2 'df -h && echo && free -h'

# Refresh output at an interval.

Limit runtime of command
timeout 30s curl -I https://example.com

# Stop a command after a maximum duration.