A comprehensive reference for the Linux command line. Covers Bash (and most POSIX shells), core utilities, and essential workflows. Commands are shown with com…
A comprehensive reference for the Linux command line. Covers Bash (and most POSIX shells), core utilities, and essential workflows. Commands are shown with common options; always check man <command> or <command> --help for full details.
1. Getting Help
| Command |
Description |
man <command> |
Full manual page |
man -k <keyword> / apropos <keyword> |
Search man pages by keyword |
<command> --help / -h |
Short help |
info <command> |
Info documentation (often more detailed) |
whatis <command> |
One-line description |
type <command> |
Show if command is builtin, alias, or external |
which <command> |
Path to executable |
whereis <command> |
Binary, source, and man page locations |
help <builtin> |
Help for shell builtins |
2. Navigation & Directory Management
pwd # Print working directory
cd /path/to/dir # Change directory
cd # Go to $HOME
cd ~ # Same as above
cd - # Go to previous directory
cd .. # Parent directory
cd ../.. # Two levels up
ls # List files
ls -l # Long format
ls -la / ls -al # All files (including hidden) + long
ls -lh # Human-readable sizes
ls -lt # Sort by modification time
ls -lS # Sort by size
ls -R # Recursive
ls -1 # One file per line
tree # Tree view (if installed)
tree -L 2 # Limit depth
mkdir dir # Create directory
mkdir -p path/to/dir # Create parent directories as needed
rmdir dir # Remove empty directory
rm -r dir # Remove directory and contents
rm -rf dir # Force recursive remove (dangerous)
Useful aliases many people set:
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
3. File Operations
touch file # Create empty file or update timestamp
cp file1 file2 # Copy
cp -r dir1 dir2 # Recursive copy
cp -a src dest # Archive mode (preserves permissions, timestamps, etc.)
cp -i # Interactive (prompt before overwrite)
mv old new # Move / rename
mv -i # Interactive
rm file # Delete file
rm -i file # Interactive
rm -rf dir # Recursive force delete (use with extreme caution)
ln -s target link # Create symbolic link
ln target link # Create hard link
stat file # Detailed file metadata
file file # Determine file type
basename /path/to/file # Filename only
dirname /path/to/file # Directory only
realpath file # Absolute path
readlink -f symlink # Resolve symlink to real path
Bulk operations:
cp file{1,2,3}.txt dest/ # Brace expansion
cp file{A..Z}.txt dest/
mv *.log logs/ # Wildcards
find . -name "*.tmp" -delete # Find + delete
4. Viewing & Examining Files
cat file # Print entire file
cat -n file # With line numbers
tac file # Reverse order
less file # Paginate (q to quit, / to search)
more file # Simpler pager
head file # First 10 lines
head -n 20 file # First 20 lines
tail file # Last 10 lines
tail -n 20 file # Last 20 lines
tail -f file # Follow (live updates)
tail -F file # Follow + retry if rotated
nl file # Number lines
wc file # Word/line/byte count
wc -l file # Line count only
od -c file # Octal dump (view binary)
hexdump -C file # Hex + ASCII
strings file # Extract printable strings
Multiple files:
cat file1 file2 > combined
less file1 file2 # Browse multiple
5. Searching
find
find /path -name "pattern" # Exact name (case-sensitive)
find /path -iname "pattern" # Case-insensitive
find . -type f # Files only
find . -type d # Directories only
find . -mtime -7 # Modified in last 7 days
find . -mtime +30 # Older than 30 days
find . -size +100M # Larger than 100 MB
find . -size -1k # Smaller than 1 KB
find . -user username # Owned by user
find . -perm 644 # Exact permissions
find . -perm -644 # At least these permissions
find . -name "*.log" -exec rm {} \; # Execute command on results
find . -name "*.log" -delete # Delete matching
find . -empty # Empty files/dirs
grep
grep "pattern" file
grep -i "pattern" file # Case-insensitive
grep -r "pattern" dir/ # Recursive
grep -n "pattern" file # Show line numbers
grep -v "pattern" file # Invert match
grep -l "pattern" * # Files containing match
grep -c "pattern" file # Count matches
grep -A 3 -B 2 "pattern" file # Context (after/before)
grep -E "pat1|pat2" file # Extended regex
grep -P "\d+" file # Perl-compatible regex
grep --color=auto "pattern" file
Other search tools
locate filename # Fast database search (run updatedb first)
which command
whereis command
ack "pattern" # Better code search (if installed)
ag "pattern" # The Silver Searcher
rg "pattern" # ripgrep (very fast)
6. Permissions & Ownership
ls -l # View permissions
chmod 755 file # Set exact mode (rwxr-xr-x)
chmod u+x file # Add execute for owner
chmod g-w file # Remove write for group
chmod o=r file # Set others to read-only
chmod -R 755 dir/ # Recursive
chown user file # Change owner
chown user:group file # Owner and group
chown -R user:group dir/
chgrp group file # Change group only
umask # View current umask
umask 022 # Set umask
Permission numbers:
4 = read (r)
2 = write (w)
1 = execute (x)
- Owner / Group / Others → e.g.
755 = rwxr-xr-x
Special bits:
chmod u+s file # Setuid
chmod g+s dir # Setgid
chmod +t dir # Sticky bit
7. Redirection, Pipes & Operators
command > file # Overwrite stdout
command >> file # Append stdout
command 2> file # Redirect stderr
command &> file # Redirect both stdout + stderr
command > file 2>&1 # Same as above (classic)
command < file # Redirect stdin
command << EOF # Here-document
...
EOF
command <<< "string" # Here-string
command1 | command2 # Pipe stdout of 1 to stdin of 2
command1 |& command2 # Pipe both stdout and stderr
command1 && command2 # Run 2 only if 1 succeeds
command1 || command2 # Run 2 only if 1 fails
command1 ; command2 # Run sequentially
Useful combinations:
command > /dev/null 2>&1 # Discard all output
command | tee file # Print and save
command | tee -a file # Append version
8. Text Processing
sort file
sort -n file # Numeric sort
sort -r file # Reverse
sort -k2 file # Sort by 2nd column
uniq file # Remove consecutive duplicates
sort file | uniq # Unique lines
sort file | uniq -c # Count occurrences
cut -d':' -f1 /etc/passwd # Cut fields
cut -c1-10 file # Cut characters
awk '{print $1}' file # Print first field
awk -F: '{print $1}' file # Custom delimiter
sed 's/old/new/' file # Replace first occurrence
sed 's/old/new/g' file # Global replace
sed -i 's/old/new/g' file # In-place edit
sed -n '10,20p' file # Print lines 10-20
tr 'a-z' 'A-Z' < file # Translate characters
tr -d '\n' < file # Delete characters
paste file1 file2 # Merge lines side-by-side
join file1 file2 # Join on common field
diff file1 file2 # Show differences
diff -u file1 file2 # Unified diff
comm file1 file2 # Compare sorted files
Column / formatting:
column -t file # Align columns
fmt file # Reformat paragraphs
fold -w 80 file # Wrap lines
9. Process Management
ps # Current shell processes
ps aux # All processes (BSD style)
ps -ef # All processes (System V style)
ps aux | grep name # Find process
pgrep name # Process IDs by name
pkill name # Kill by name
kill PID # Terminate process
kill -9 PID # Force kill (SIGKILL)
kill -15 PID # Graceful (SIGTERM)
killall name # Kill all matching name
top # Interactive process viewer
htop # Better top (if installed)
btop / btm # Modern alternatives
jobs # List background jobs
bg %1 # Resume job 1 in background
fg %1 # Bring job 1 to foreground
Ctrl+Z # Suspend current process
nohup command & # Run immune to hangups
disown # Remove job from shell table
nice -n 10 command # Run with lower priority
renice -n 5 PID # Change priority of running process
Resource limits:
ulimit -a # Show all limits
ulimit -n 4096 # Set open files limit
10. System Information
uname -a # Kernel and system info
hostname # Hostname
hostnamectl # More detailed (systemd)
uptime # How long system has been up
whoami # Current user
id # User and group IDs
w / who # Logged-in users
last # Login history
date # Current date/time
cal # Calendar
timedatectl # Timezone and NTP status
df -h # Disk space (human-readable)
df -i # Inode usage
du -sh dir # Directory size
du -h --max-depth=1 # Sizes one level deep
free -h # Memory usage
lscpu # CPU info
lsblk # Block devices
lsusb # USB devices
lspci # PCI devices
dmidecode # Hardware info (needs root)
cat /etc/os-release # Distribution info
cat /proc/cpuinfo
cat /proc/meminfo
cat /proc/version
11. Disk & Filesystem
fdisk -l # List partitions (root)
lsblk -f # Filesystems and UUIDs
mount # Show mounted filesystems
mount /dev/sdX /mnt # Mount
umount /mnt # Unmount
umount -l /mnt # Lazy unmount
df -hT # Filesystem types
tune2fs -l /dev/sdX # Ext filesystem info
fsck /dev/sdX # Check filesystem (unmounted)
badblocks /dev/sdX # Check for bad blocks
Create filesystems:
mkfs.ext4 /dev/sdX
mkfs.xfs /dev/sdX
mkfs.vfat /dev/sdX # FAT32
12. Networking
ip a # Show interfaces (modern)
ifconfig # Classic (if installed)
ip r # Routing table
ip link set eth0 up/down
ping host # Test connectivity
ping -c 4 host # Limited count
traceroute host
mtr host # Combined ping + traceroute
curl URL # Transfer data
curl -O URL # Download file
curl -L URL # Follow redirects
wget URL # Download
wget -c URL # Continue partial download
ssh user@host # Secure shell
scp file user@host:/path # Secure copy
scp -r dir user@host:/path
rsync -avz src/ dest/ # Efficient sync
rsync -avz -e ssh src/ user@host:/path
netstat -tuln # Listening ports (classic)
ss -tuln # Modern alternative
ss -s # Socket statistics
nmap host # Port scanning (if installed)
dig domain # DNS lookup
nslookup domain
host domain
whois domain
Firewall (examples):
# UFW (Ubuntu/Debian)
ufw status
ufw allow 22
ufw enable
# firewalld (RHEL/Fedora)
firewall-cmd --list-all
firewall-cmd --add-port=80/tcp --permanent
firewall-cmd --reload
13. Package Management
Debian / Ubuntu (apt)
sudo apt update
sudo apt upgrade
sudo apt full-upgrade
sudo apt install package
sudo apt remove package
sudo apt purge package
sudo apt autoremove
sudo apt search keyword
sudo apt show package
apt list --installed
RHEL / CentOS / Fedora (dnf / yum)
sudo dnf update
sudo dnf install package
sudo dnf remove package
sudo dnf search keyword
sudo dnf info package
sudo dnf list installed
Arch (pacman)
sudo pacman -Syu # Full system update
sudo pacman -S package
sudo pacman -R package
sudo pacman -Rs package # Remove with dependencies
sudo pacman -Ss keyword
sudo pacman -Qi package
Snap / Flatpak
snap find keyword
snap install package
flatpak search keyword
flatpak install package
14. Users, Groups & Authentication
sudo -i # Root shell
sudo -u user command # Run as another user
su - username # Switch user
passwd # Change own password
passwd username # Change another user’s password (root)
useradd username # Create user
useradd -m -s /bin/bash username
usermod -aG group username
userdel username
groupadd groupname
groups # Groups of current user
id username
who
w
last
lastb # Failed logins
SSH keys:
ssh-keygen -t ed25519 -C "comment"
ssh-copy-id user@host
cat ~/.ssh/id_ed25519.pub
15. Compression & Archives
# tar
tar -cvf archive.tar files # Create
tar -xvf archive.tar # Extract
tar -tvf archive.tar # List
tar -czvf archive.tar.gz files # gzip
tar -xzvf archive.tar.gz
tar -cJvf archive.tar.xz files # xz
tar -xJvf archive.tar.xz
# zip / unzip
zip -r archive.zip dir/
unzip archive.zip
unzip -l archive.zip
# Other
gzip file # Compress (replaces original)
gunzip file.gz
bzip2 file
bunzip2 file.bz2
xz file
unxz file.xz
16. Environment & Shell
echo $VARIABLE
export VARIABLE=value
env # All environment variables
printenv
set # Shell variables + functions
unset VARIABLE
source file / . file # Execute in current shell
history # Command history
history | grep keyword
!! # Last command
!$ # Last argument of previous command
!* # All arguments of previous command
Ctrl+R # Reverse search history
Common variables:
$HOME, $USER, $PATH, $PWD, $OLDPWD, $SHELL, $TERM, $LANG, $EDITOR
Path management:
echo $PATH
export PATH="$PATH:/new/path"
17. Job Scheduling
crontab -e # Edit current user’s crontab
crontab -l # List
crontab -r # Remove
Crontab format:
┌──────── minute (0-59)
│ ┌────── hour (0-23)
│ │ ┌──── day of month (1-31)
│ │ │ ┌── month (1-12)
│ │ │ │ ┌ day of week (0-6, Sunday=0)
│ │ │ │ │
* * * * * command
Examples:
0 2 * * * /path/to/backup.sh # Daily at 02:00
*/15 * * * * /path/to/script.sh # Every 15 minutes
0 0 * * 0 /path/to/weekly.sh # Weekly on Sunday
systemd timers (modern alternative) – see systemctl list-timers.
18. Keyboard Shortcuts (Bash / Readline)
| Shortcut |
Action |
Ctrl + A |
Beginning of line |
Ctrl + E |
End of line |
Ctrl + U |
Cut from cursor to beginning |
Ctrl + K |
Cut from cursor to end |
Ctrl + W |
Cut previous word |
Ctrl + Y |
Paste (yank) |
Ctrl + L |
Clear screen |
Ctrl + C |
Kill current process |
Ctrl + Z |
Suspend process |
Ctrl + D |
EOF / exit shell |
Ctrl + R |
Reverse history search |
Ctrl + S |
Forward history search (if not frozen) |
Alt + B / Esc + B |
Move back one word |
Alt + F / Esc + F |
Move forward one word |
Alt + D |
Delete word forward |
Tab |
Autocomplete |
Tab Tab |
Show all completions |
!! |
Repeat last command |
!n |
Run command number n from history |
!string |
Run last command starting with string |
19. Bash Scripting Essentials
#!/bin/bash
set -euo pipefail # Strict mode (recommended)
# Variables
name="value"
readonly CONST="immutable"
local var="function scope"
# Conditionals
if [[ condition ]]; then
...
elif [[ other ]]; then
...
else
...
fi
# Tests
[[ -f file ]] # File exists and is regular
[[ -d dir ]] # Directory
[[ -x file ]] # Executable
[[ -z "$str" ]] # Empty string
[[ -n "$str" ]] # Non-empty
[[ "$a" == "$b" ]]
[[ "$a" -eq "$b" ]] # Numeric equality
[[ "$a" -lt "$b" ]] # Less than
# Loops
for i in {1..10}; do ...; done
for file in *.txt; do ...; done
while read -r line; do ...; done < file
until condition; do ...; done
# Functions
myfunc() {
local arg=$1
echo "$arg"
return 0
}
# Arrays
arr=(one two three)
echo "${arr[0]}"
echo "${arr[@]}"
echo "${#arr[@]}"
20. Useful One-Liners & Patterns
# Find large files
find / -type f -size +100M -exec ls -lh {} \; 2>/dev/null
# Disk usage sorted
du -h /path | sort -hr | head -20
# Kill process by name
pkill -f "pattern"
# Watch a command
watch -n 1 'df -h'
# Continuous ping with timestamp
ping host | while read pong; do echo "$(date): $pong"; done
# Extract specific column from CSV
cut -d',' -f2 file.csv
# Count unique IPs in log
awk '{print $1}' access.log | sort | uniq -c | sort -nr
# Create directory structure
mkdir -p project/{src,bin,docs,tests}
# Quick HTTP server
python3 -m http.server 8000
# Generate random password
openssl rand -base64 24
21. Safety & Best Practices
- Prefer
rm -i or trash-cli over raw rm -rf.
- Always quote variables:
"$var".
- Use
set -euo pipefail in scripts.
- Prefer
[[ ]] over [ ] in Bash.
- Test destructive commands with
echo first.
- Keep backups before mass changes.
- Use version control for scripts and configs.
- Prefer absolute paths in cron and scripts.
- Read man pages for the exact options you need.
22. Quick Reference – Exit Codes
| Code |
Meaning |
| 0 |
Success |
| 1 |
General error |
| 2 |
Misuse of shell builtin |
| 126 |
Command found but not executable |
| 127 |
Command not found |
| 128+n |
Signal n (e.g. 130 = Ctrl+C / SIGINT) |
| 255 |
Exit status out of range |
Check with echo $? after any command.
Pro tip: Create your own ~/.bash_aliases or ~/.zshrc with the aliases and functions you use most. Keep this cheat sheet handy and expand it as you discover new tools (fzf, bat, eza, ripgrep, fd, httpie, etc.).
Happy terminaling!