Master the command line with this comprehensive guide to essential Linux commands for beginners and intermediate users.
Page
Linux Commands
File & Directory Management
Basic Navigation
pwd— Print working directory (show current path)
pwd
# Output: /home/user/project
ls— List directory contentsls # Simple listing ls -l # Long format with details ls -a # Show hidden files (starting with .) ls -lh # Human-readable file sizescd— Change directorycd /path/to/dir # Absolute path cd ../.. # Go up two levels cd ~ # Home directory cd - # Previous directorymkdir— Create directoriesmkdir new_folder # Single directory mkdir -p a/b/c # Nested directories (parents)rmdir— Remove empty directoriesrmdir old_folder
File Operations
touch— Create or update file timestampstouch newfile.txt # Create empty file touch -t 202412311200.00 f # Set specific timestampcp— Copy files/directoriescp source.txt dest.txt # File copy cp -r src_dir/ dest_dir/ # Directory recursive copy cp -i file1 dir/ # Interactive (prompt before overwrite)mv— Move or rename files/directoriesmv oldname.txt newname.txt # Rename mv file.txt /path/to/dir/ # Move to directoryrm— Remove files/directoriesrm file.txt # Delete single file rm -r folder_name # Recursive delete (directory) rm -rf path_to_dir # Force recursive delete rm -i * # Interactive confirmation for allln— Create linksln source linkname # Hard link ln -s target symlink_name # Symbolic (soft) link
File Viewing & Editing
cat— Concatenate and display filescat file.txt # Display entire file cat > newfile.txt # Create from stdin cat file1 file2 >> combined.txt # Append multiple filesless/more— Page through large filesless logfile.log # Scrollable viewer (q to quit) more bigfile.txt # Basic pagerhead/tail— View beginning or end of filehead -20 file.txt # First 20 lines tail -f logfile.log # Follow log (real-time updates) tail -100 access.log # Last 100 linesnano/vim— Terminal text editorsnano file.txt # Simple editor vim file.txt # Advanced modal editor
File Search & Find
find— Locate files by name, type, size, etc.find . -name "*.txt" # Find all text files in current dir find /home -user john # Files owned by user 'john' find /var/log -size +10M # Files larger than 10MB find . -type f -mtime -7 # Regular files modified in last 7 daysgrep— Search text patternsgrep "error" logfile.txt # Find lines containing 'error' grep -i "warning" file # Case-insensitive search grep -r "function" src/ # Recursive directory search grep -c "pattern" file # Count matching lineslocate— Fast filename lookup (uses database)locate nginx.conf # Quick file location sudo updatedb # Update the locate database first
Process & System Monitoring
Process Management
ps— Snapshot of current processesps # Simple process list ps aux # Full format (BSD style) ps -ef # Full format (UNIX style) ps -p PID # Specific process by IDtop/htop— Real-time process viewertop # Basic real-time monitor htop # Enhanced interactive version (if installed)kill/killall— Terminate processeskill PID # Send SIGTERM to process ID kill -9 PID # Force kill (SIGKILL) killall nginx # Kill all processes named 'nginx' pkill firefox # Kill by name patternbg/fg— Job control in terminalsleep 100 & # Run background job bg %1 # Resume job as background fg %1 # Bring to foreground jobs # List current jobs
System Resources
df— Disk space usagedf # Basic disk info df -h # Human-readable sizes (GB/MB) df -T # Show filesystem typesdu— Directory size analysisdu -sh /path/to/dir # Summarize directory size du --max-depth=1 # Limit depth of scan du -h | sort -rh | head # Top largest directoriesfree— Memory usagefree # Basic memory info free -h # Human-readable (MB/GB) free -m # Megabytes onlyuptime/w— System load and usersuptime # Load average, uptime, user count w # Who's logged in with activity who # Logged-in users listvmstat/iostat— Virtual memory & I/O statsvmstat 1 # Report every second iostat -x # Extended CPU and device stats
User & Permission Management
Users & Groups
useradd/adduser— Create usersuseradd newuser # Basic user creation (Debian/Ubuntu) adduser newuser # Interactive setup (preferred on Debian-based) useradd -m -s /bin/bash username # With home directory and shellusermod— Modify existing usersusermod -aG sudo john # Add 'john' to sudo group usermod -d /home/john2 john # Change home directory usermod -L username # Lock account (disable password)userdel— Remove usersuserdel username # Delete user without home dir userdel -r username # Delete with home and mail spoolpasswd— Manage passwordspasswd # Change own password sudo passwd username # Set another user's password passwd -e username # Force password change at next login chage -l username # Show password aging infogroups/id— Group and identity checksgroups # Groups for current user id # UID, GID, and group memberships getent passwd # View all users from system databases
Permissions & Ownership
chmod— Change file permissions (mode)chmod u+rwx file # Add read/write/execute for owner chmod g-wx file # Remove write and execute for group chmod o=r file # Set others to read-only # Numeric mode examples: chmod 755 script.sh # rwxr-xr-x (owner: full, others: read+exec) chmod 644 document.txt # rw-r--r-- chmod +x file # Add execute permissionchown— Change owner and groupchown user file # Change owner only chown :group file # Change group only chown user:group file # Change both # Recursive ownership change: sudo chown -R www-data:www-data /var/www/htmlchgrp— Change group specificallychgrp developers project/ # Set directory to 'developers' group
Networking Commands
Connectivity & Diagnostics
ping— Test network connectivityping google.com # Send ICMP echo requests ping -c 4 google.com # Limit to 4 packets ping -W 2 host # Set timeout (seconds)traceroute/tracepath— Trace network pathtraceroute example.com # Show all hops to destination tracepath hostname # Alternative without root privilegesnslookup/dig— DNS lookupsnslookup google.com # Query DNS server for IP dig +short google.com # Get only the A record (IP) dig @8.8.8.8 example.com # Use specific DNS serverhost— Simple DNS lookup toolhost example.com # Quick hostname to IP resolution
Network Interfaces & Configuration
ip/ifconfig— View and configure interfaces (modern vs legacy)ip a # Show all addresses (preferred modern) ip addr show eth0 # Specific interface details ifconfig # Legacy tool (may need installation) # Configure IP: sudo ip addr add 192.168.1.50/24 dev eth0netstat/ss— Network connections and socketsnetstat -tuln # List listening TCP ports (legacy) ss -tulpn # Modern replacement for netstat ss -s # Socket statistics summarycurl/wget— Download files from webcurl https://example.com/file.zip # Transfer data with URL syntax wget http://site.com/largefile.iso # Simple file downloader (resume: -c) # Advanced usage: curl -O http://server.com/file # Download and save original filenamessh— Secure shell remote accessssh user@hostname # Connect to remote server ssh -p 2222 user@host # Custom port connection scp file.txt user@remote:/path/ # Copy files via SSH # Key-based auth setup: ssh-keygen # Generate RSA key pair ssh-copy-id user@hostname # Install public key on remotescp/rsync— Secure file transfer and syncscp local.txt user@remote:/dest/ # Simple secure copy rsync -avz ./local_dir/ user@host:/remote/path/ # Sync with compression (-z) and archive mode # Exclude patterns: rsync -av --exclude='*.tmp' src/ dest/nc(Netcat) — Network debugging utilitync -zv host port # Check if port is open echo "hello" | nc localhost 80 # Send data to service
Firewalls & Security
ufw— Uncomplicated Firewall (Ubuntu/Debian)ufw status # Show firewall state ufw allow ssh # Allow SSH access ufw allow from 192.168.1.0/24 # Allow subnet sudo ufw enable # Activate firewall (careful!)iptables— Low-level packet filter (advanced)iptables -L # List current rules iptables -A INPUT -p tcp --dport 22 -j ACCEPT # Allow SSH sudo iptables-save # Persist rules to file # Flush all rules: sudo iptables -F # Warning: clears everything!firewall-cmd— Firewalld (RHEL/CentOS/Fedora)firewall-cmd --list-all # Show current zones and services sudo firewall-cmd --permanent --add-service=http # Add HTTP service permanently sudo firewall-cmd --reload # Apply changes
Package Management (Distribution-Specific)
Debian/Ubuntu-based Systems (`apt` / `dpkg`)
# Update package lists and upgrade packages:
sudo apt update # Refresh repository metadata
sudo apt upgrade # Upgrade installed packages
sudo apt full-upgrade # Smart upgrade with dependency changes
# Install, remove, search packages:
sudo apt install vim # Install a package
sudo apt remove vim # Remove (keep config files)
sudo apt purge vim # Remove completely (including configs)
apt list --installed | grep nginx # Search installed packages
apt-cache policy nginx # Show available versions and sources
# Clean up:
sudo apt autoremove # Remove unused dependencies
sudo apt clean # Clear downloaded package cache
# Low-level dpkg commands:
dpkg -i package.deb # Install .deb file locally
dpkg -l | grep vim # List installed packages matching pattern
dpkg --configure -a # Fix broken installations
Red Hat/CentOS/Fedora (`dnf` / `yum`)
# DNF (modern, Fedora/RHEL 8+, CentOS Stream):
sudo dnf update # Update all packages
sudo dnf install httpd # Install package
sudo dnf remove nginx # Remove package
sudo dnf search python3 # Search repositories for packages
dnf history # View transaction history
dnf history undo ID # Undo a previous installation/upgrade
# YUM (legacy, RHEL 7 and older):
sudo yum update # Legacy command (still works on many systems)
Arch Linux (`pacman`)
sudo pacman -Syu # Sync database and upgrade all packages
sudo pacman -S firefox # Install package
sudo pacman -Rns firefox # Remove with dependencies (--recursive, --nosave configs)
pacman -Qs python # Query installed packages (search local DB)
pacman -Si nginx # Show info about a repository package
OpenSUSE (`zypper`)
sudo zypper refresh # Update repositories
sudo zypper install vim # Install package
sudo zypper remove nano # Remove package
zypper search python # Search for packages in repos
Text Processing & Utilities
Stream Editors & Filters
sed— Stream editor (in-place editing, substitutions)sed 's/old/new/g' file.txt # Replace all occurrences of old with new sed -i.bak 's/foo/bar/' file # Edit in place and create backup (.bak) sed -n '/pattern/p' log # Print only lines matching patternawk— Pattern scanning and processing languageawk '{print $1}' file.txt # Print first column awk '$3 > 100 {sum += $3} END {print sum}' data # Sum third column if > 100 awk -F: '{print $1, $7}' /etc/passwd # Use colon as field separatorcut— Extract sections from lines (field-based)cut -d':' -f1 /etc/passwd # First field using ':' delimiter cut -c5-10 file.txt # Characters 5 through 10 onlysort/uniq— Sort and remove duplicatessort names.txt # Alphabetical sorting sort -n numbers.txt # Numerical sorting uniq file.txt # Remove adjacent duplicate lines (input must be sorted) # Combined: cat list.txt | sort | uniq # Unique entries from unsorted inputwc— Word, line, character countwc -l file.txt # Count lines only wc -w # Words (whitespace-separated) wc -c # Characters/bytes wc -m # Multibyte characterstr— Translate or delete charactersecho "hello world" | tr 'a-z' 'A-Z' # Convert to uppercase cat file.txt | tr -d '\r' # Remove carriage returns (Windows line endings)
Compression & Archiving
tar— Tape archive utility (most common archiver)tar -cvf archive.tar files... # Create uncompressed archive (-c create, -v verbose, -f file) tar -xvf archive.tar # Extract all files (-x extract) tar -tzf archive.tar.gz # List contents of compressed archive (-t list) # Common compression flags: tar -czvf backup.tar.gz dir/ # Compress with gzip tar -cjvf backup.tar.bz2 dir/ # Compress with bzip2 (slower but better ratio) tar -cJvf archive.xz files # XZ compression (best ratio, slowest) # Extract specific file: tar -xzf archive.tar.gz path/to/file.txtgzip/gunzip— Compress single filesgzip largefile.log # Creates largefile.log.gz (original removed by default) gunzip largefile.log.gz # Decompress back to original name zcat file.log.gz # View compressed content without extracting # Keep original: gzip -k file.txt # Compress but keep source filebzip2/xz— Alternative compression formats (better ratio, slower)bzip2 data.txt # Creates .bz2 compressed version xz archive.tar # XZ compression (.xz extension) # Decompress: bunzip2 file.bz2 # Unbzip2 unxz file.xz # Unxz (or xz -d)zip/unzip— Cross-platform archive formatzip archive.zip folder/* # Create ZIP with all contents of folder/ unzip archive.zip # Extract to current directory # Advanced: zip -r backup.zip project/ # Recursive compression (directories) unzip -l archive.zip # List contents without extractingdiff/patch— Compare and apply differences between filesdiff file1.txt file2.txt # Show line-by-line differences diff -u old new > changes.patch # Unified format patch file (-u) # Apply patches: patch < changes.patch # Interactive application patch -p0 < changes.patch # Apply without path strippingcmp— Binary comparison of two filescmp file1.bin file2.bin # Find first differing byte cmp -l file1 file2 # List all differences (byte by byte)
Shell Utilities & Shortcuts
Environment Variables
export/env— Manage environment variablesexport MY_VAR="hello world" # Set variable for current shell session echo $MY_VAR # View value (note: no quotes needed) env # Show all exported variables printenv # Alternative to show environment # Persistent across sessions: echo 'export PATH=$PATH:/custom/bin' >> ~/.bashrc # Add to bash config source ~/.bashrc # Reload configuration without restartalias/unalias— Create command shortcutsalias ll='ls -la' # Shorten ls -l with all details alias gs='git status' # View aliases: alias # List current aliases unalias my_alias # Remove temporary alias (current session only) # Make permanent: add to ~/.bashrc or ~/.zshrchistory— Command history managementhistory # Show command history with line numbers !123 # Re-execute command number 123 from history !! # Repeat last command !$ # Last argument of previous command (shortcut) # Search and manage: Ctrl+R # Reverse search through history interactively history -c # Clear current session's historytime— Measure execution durationtime sleep 5 # Time how long a command takes # Output format: real elapsed wall-clock time user CPU time spent in user mode sys CPU time spent in kernel modewatch— Execute commands repeatedly with output refreshwatch -n 5 df -h # Run every 5 seconds (default is 2s) watch --color 'free -m' # Colorized output for memory monitoring
Input/Output Redirection & Pipes
>/>>— Redirect stdout to file (overwrite vs append)echo "hello" > test.txt # Overwrite existing content echo "world" >> test.txt # Append to end of file command > output.log # Save program output to log file # Multiple redirections: ls -la > files.txt 2> errors.txt # stdout and stderr separately|— Pipe (connect stdout of one command to stdin of next)ps aux | grep nginx # Filter process list for 'nginx' cat logfile.log | tail -50 # Show last 50 lines via pipe echo "data" | tr '[a-z]' '[A-Z]' # Transform text through pipeline # Common pipelines: ls -lh | grep .pdf # List PDF files with human-readable sizes free -h | awk '/^Mem:/ {print $3}' # Extract used memory only (awk filters)&— Run command in background, wait for all jobs to completesleep 10 & # Background job echo "done" # Continue immediately while sleep runs # Wait for specific process: wait PID # Block until specified process finishes&&/||— Conditional execution (AND/OR)cd /var/log && ls # Run 'ls' only if 'cd' succeeds make clean || echo "clean failed" # Show error message on failure # Complex chains: git pull && npm install && npm run build # Chain multiple commands (all must succeed);— Run next command regardless of previous resultcd /tmp ; ls # Always execute 'ls' even if directory change fails echo "start" ; sleep 2 ; echo "end"
Special & Administrative Commands
System Control
reboot/shutdown— Restart or power off systemreboot # Immediate restart (requires sudo) shutdown now # Power off immediately // Scheduled operations: shutdown -h +10 // Halt in 10 minutes shutdown -r 23:59 // Reboot at specific time (HH:MM format)systemctl— Systemd service manager (modern Linux systems)systemctl status nginx # Check service state and logs sudo systemctl start httpd // Start a service sudo systemctl stop mysql // Stop a service sudo systemctl restart ssh // Restart a service // Enable/disable at boot: sudo systemctl enable docker // Auto-start on boot sudo systemctl disable cron // Disable auto-start // View all services: systemctl list-units --type=service --state=runningjournalctl— Systemd journal log viewerjournalctl -xe // Recent errors with context journalctl -u nginx // Logs for specific service (unit) // Real-time follow: journalctl -f // Follow live logs (like tail -f) journalctl --since "10 min ago" // Filter by time rangedmesg— Kernel ring buffer messagesdmesg // Show kernel boot and hardware messages dmesg | grep USB // Search for specific events (e.g., USB devices) // Clear old logs: sudo dmesg -C // Clear console log bufferwho/last— User session trackingwho // Currently logged-in users with terminals last // Historical login records (from wtmp) last reboot // Show system reboots from history // Recent activity: last -10 // Last 10 logins onlydate/cal— Date and calendar utilitiesdate // Current date/time (default format) date +%Y-%m-%d // Custom format: YYYY-MM-DD // Calendar: cal // Show current month's calendar cal -3 // Display three months at once cal 2025 // Full year calendar for specific yearbc— Basic calculator (arithmetic in shell)echo "10 + 5" | bc // Simple arithmetic: result = 15 // Advanced math: echo "scale=2; 3.14 * 7" | bc // Floating point with precision control // Interactive mode: bc // Enter calculator shell (Ctrl+D to exit)dd— Low-level data conversion and copyingdd if=/dev/sdX of=backup.img bs=4M // Create disk image backup // Write ISO to USB: sudo dd if=fedora.iso of=/dev/sdb bs=4M status=progress // Verify data integrity (compare source and destination): diff <(dd if=file1.img bs=512 count=10) <(dd if=file2.img bs=512 count=10)locale/envsubst— Localization and variable substitutionlocale // Show current locale settings (language, encoding) // Set temporary environment: LANG=en_US.UTF-8 command // Run with specific language setting only for this command
Quick Reference Tables
File Operations Cheat Sheet
| Command | Description | Example |
|---|---|---|
ls |
List directory contents | ls -la /home/user/ |
cd |
Change working directory | cd ~/projects/webapp |
pwd |
Show current path | pwd → /home/user/projects |
mkdir |
Create new directory | mkdir backup_2026 |
rmdir |
Remove empty directory | rmdir old_folder/ |
touch |
Create/update file timestamp | touch notes.txt |
cp |
Copy files/directories | cp -r src/ dest/ |
mv |
Move or rename | mv oldname newname |
rm |
Remove files (recursive with -r) |
rm -rf temp_dir/ |
ln |
Create links (-s for symbolic) |
ln -s target link_name |
Process Management Cheat Sheet
| Command | Description | Example |
|---|---|---|
ps aux |
Show all running processes | `ps aux |
top / htop |
Real-time process monitor | htop (interactive) |
kill PID |
Send signal to terminate | kill 12345 or kill -9 PID |
pkill name |
Kill by process name | pkill firefox |
bg/fg |
Job control (background/foreground) | jobs, fg %1 |
Package Manager Cheat Sheet
| Distribution | Install Command | Update Command | Remove Command |
|---|---|---|---|
Debian/Ubuntu (apt) |
sudo apt install pkg |
sudo apt update && sudo apt upgrade |
sudo apt remove pkg |
RHEL/CentOS/Fedora (dnf/yum) |
sudo dnf install pkg |
sudo dnf update |
sudo dnf remove pkg |
Arch Linux (pacman) |
sudo pacman -S pkg |
sudo pacman -Syu |
sudo pacman -Rns pkg |
OpenSUSE (zypper) |
sudo zypper install pkg |
sudo zypper refresh && sudo zypper update |
sudo zypper remove pkg |
Network Commands Cheat Sheet
| Command | Description | Example |
|---|---|---|
ping host |
Test connectivity | ping google.com -c 4 |
ip a / ifconfig |
Show network interfaces | ip addr show eth0 |
ss -tulpn |
List listening ports (modern) | `ss -tulnp |
curl URL |
Transfer data from web | curl -O http://example.com/file.zip |
wget URL |
Download files | wget https://site.com/large.iso |
ssh user@host |
Remote shell access | ssh admin@example.org |
scp file user@host:path/ |
Secure copy via SSH | scp local.txt root@server:/tmp/ |
Troubleshooting Common Issues
"Command not found" Error
# Check if command exists in PATH:
which ls # Should return /bin/ls or similar
command -v mycmd # Alternative check (works with aliases too)
# If missing, install via package manager:
sudo apt install bash // Debian-based systems
sudo dnf install bash // RHEL/Fedora/CentOS
Permission Denied Errors
# Check current permissions and ownership:
ls -l file.txt # Shows: owner group perms size date name
stat file.txt # Detailed metadata including inode info
# Fix with sudo (if you have privileges):
sudo chown user:group file // Change ownership
sudo chmod u+x script.sh // Add execute permission for owner
Disk Space Full
# Find largest directories:
du -sh /* | sort -rh # Human-readable, sorted by size
df -h // Check mounted filesystem usage
find /var/log -type f -size +100M // Large log files to clean up
Slow Performance or High Load
# Identify resource hogs:
top // Interactive process viewer (press 'P' for CPU, 'M' for memory)
vmstat 5 // Virtual memory stats every 5 seconds
iostat -x 2 // I/O statistics with device details
Network Connectivity Issues
# Step-by-step diagnostics:
ping google.com // Test basic connectivity (ICMP echo)
curl -v http://example.com // Verbose HTTP request to test web access
nslookup example.com // Verify DNS resolution works
traceroute example.com // Trace network path and identify where packets drop
Best Practices & Tips
1. Always Use `--help` or Manual Pages First
cp --help // Quick usage summary for any command
man cp // Full manual page with all options
info ls // GNU info system (alternative to man)
2. Verify Before Deleting Large Directories
# Preview what will be deleted:
du -sh /path/to/delete // Show total size before removal
tar -tzf archive.tar.gz // List contents without extracting first
find . -name "*.tmp" // Find temporary files to clean up
3. Use `sudo` Sparingly but Strategically
- Only use
sudowhen necessary (not for every command) - Check what a command does before running with elevated privileges:
cat /etc/passwd // Read-only operation, often doesn't need sudo
rm -rf /var/cache/apt // Dangerous without review!
sudo rm -rf /var/cache/apt // Only after confirming contents are safe to remove
4. Create Aliases for Frequent Commands
Add these to ~/.bashrc or ~/.zshrc:
alias ll='ls -la'
alias h='history | grep '
alias gs='git status'
alias gdiff='git diff --color-words' // Git-friendly diff for code review
Then reload: source ~/.bashrc
5. Use Pipes to Chain Simple Tools Instead of Complex Scripts
# Instead of writing a script, chain commands:
cat access.log | grep "404" | awk '{print $1}' | sort -u > broken_links.txt
This approach is faster for one-off tasks and easier to debug.
6. Backup Before Major Changes
tar czf /backup/config_backup.tar.gz /etc/nginx/
sudo cp /etc/passwd /etc/passwd.backup_$(date +%Y%m%d)
Always create backups before editing critical system files or running destructive commands.
7. Log Your Commands for Auditing
script session.log // Record entire terminal session to file
tee output.txt // Save command output while still displaying it on screen
history > ~/command_history_$(date +%Y%m%d).txt // Export history periodically
Next Steps & Further Learning
- Shell Scripting: Learn
bashscripting for automation (variables, loops, conditionals) - Systemd Deep Dive: Master service management with
systemctl, timers, and units - Advanced Networking: Explore
iptables,firewalld, and network namespaces - Performance Tuning: Study
strace,perf, and kernel parameters (sysctl) - Containerization: Learn Docker/Podman for isolated environments
- Version Control: Master Git workflows alongside Linux CLI skills
This guide covers the most essential commands used daily by system administrators, developers, and power users. Practice regularly to build muscle memory and efficiency. 🚀
More in this section