Table of Contents
- Understanding the Shell
- Essential Navigation Commands
- File & Directory Operations
- Text Manipulation Tools
- Process Management
- Package Management
- Networking Essentials
- Automation with Shell Scripts
- Pro Tips & Productivity Hacks
- Conclusion
- References
1. Understanding the Shell
Before diving into commands, it’s critical to understand what the “shell” is. The shell is a command-line interpreter that translates your typed commands into instructions the Linux kernel can execute. Think of it as a dialogue between you and the operating system.
Common Shells
Linux systems support multiple shells, each with unique features. The most popular are:
- Bash (Bourne-Again SHell): Default on most Linux distributions (Ubuntu, Debian, Fedora).
- Zsh (Z Shell): Offers advanced features like better autocompletion and themes (popular among developers).
- Fish (Friendly Interactive SHell): Designed for simplicity and user-friendliness.
To check your current shell, run:
echo $SHELL
To switch shells (if installed), type the shell name (e.g., zsh). To make it permanent, use chsh -s /bin/zsh (replace /bin/zsh with your shell’s path).
2. Essential Navigation Commands
Navigating the Linux filesystem is the first step to command-line proficiency. Here are the tools you’ll use daily:
pwd: Print Working Directory
Shows your current location in the filesystem.
pwd
# Output: /home/yourusername/documents
ls: List Directory Contents
Lists files and folders in the current directory. Customize with flags:
-l: Long format (shows permissions, owner, size, date).-a: Show hidden files (those starting with.).-h: Human-readable sizes (e.g., 1K, 2M instead of bytes).-t: Sort by modification time (newest first).
Example:
ls -lah
# Output:
# drwxr-xr-x 2 user user 4.0K Sep 10 14:30 docs
# -rw-r--r-- 1 user user 12K Sep 10 10:15 notes.txt
# .hiddenfile
cd: Change Directory
Move between directories. Use absolute paths (full path from /) or relative paths (relative to current directory):
cd /home/user/documents # Absolute path
cd ../downloads # Relative path (move up one folder, then into downloads)
cd ~ # Shortcut for home directory
cd - # Go back to the previous directory
3. File & Directory Operations
Creating, copying, moving, and deleting files/directories are core tasks. Master these to manage your filesystem efficiently.
mkdir: Create Directories
Make a new directory:
mkdir projects # Single directory
mkdir -p work/reports/2024 # -p creates parent directories if missing (no errors if they exist)
touch: Create Empty Files
Quickly create blank files (or update timestamps of existing files):
touch todo.txt
touch report_{jan,feb,mar}.pdf # Create multiple files at once (brace expansion)
cp: Copy Files/Directories
Copy files with cp source destination. For directories, add -r (recursive):
cp notes.txt backup/ # Copy file to backup folder
cp -r projects/ /external-drive/ # Copy entire projects directory (with subfolders)
cp -v file.txt ~/docs/ # -v (verbose) shows progress
mv: Move/Rename Files
Move files to a new location or rename them:
mv oldname.txt newname.txt # Rename a file
mv report.pdf ~/documents/ # Move file to documents folder
mv *.txt archives/ # Move all .txt files to archives (wildcard *)
rm: Delete Files/Directories
Caution: rm is permanent—no trash bin! Use carefully:
rm oldfile.txt # Delete a file
rm -r oldfolder/ # Delete a directory and its contents (recursive)
rm -f stubbornfile.txt # -f (force) deletes read-only files without prompting
rm -i *.log # -i (interactive) prompts before deleting (safer!)
Pro Tip: Avoid rm -rf / (deletes everything!)—always double-check paths.
4. Text Manipulation Tools
Linux excels at text processing. These tools let you search, edit, and analyze text files efficiently.
cat: Concatenate/View Files
Display file contents or combine files:
cat notes.txt # View a file
cat part1.txt part2.txt > full.txt # Combine part1 and part2 into full.txt (>)
less: Read Large Files
For big files (e.g., logs), less lets you scroll without overwhelming the terminal:
less /var/log/syslog # Navigate with arrow keys; press q to quit
head/tail: View Start/End of Files
Quickly check the first/last lines of a file:
head -n 5 report.txt # Show first 5 lines (default: 10)
tail -f /var/log/auth.log # -f "follows" the file, showing new lines in real-time (great for logs!)
grep: Search Text in Files
Find patterns in files with grep "pattern" file. Use flags for flexibility:
grep "error" app.log # Find "error" in app.log
grep -i "Error" app.log # -i (case-insensitive)
grep -r "critical" /var/log/ # -r (recursive) search in /var/log and subfolders
grep -n "warning" system.log # -n shows line numbers
sed: Stream Editor
Edit text in-place or via pipes. Common use: replace text:
sed 's/old/new/g' file.txt # Replace "old" with "new" globally (g=global)
sed -i 's/error/ERROR/g' app.log # -i (in-place) edit the file directly
awk: Pattern Scanning & Processing
Powerful for parsing structured text (e.g., CSVs, logs). Extract columns with $N (N=column number):
awk '{print $1, $3}' data.csv # Print columns 1 and 3 of data.csv
awk '/error/ {print $0}' app.log # Print lines containing "error" (entire line: $0)
5. Process Management
Monitor and control running programs (processes) to troubleshoot slow systems or kill unresponsive apps.
ps: List Running Processes
View active processes. Use flags for details:
ps aux # a=all users, u=detailed info, x=include processes without a terminal
# Output includes PID (Process ID), CPU/memory usage, and command
top/htop: Real-Time Process Monitoring
top shows a dynamic view of system resource usage. For a friendlier interface, install htop (use sudo apt install htop or sudo dnf install htop):
top # Press q to quit; sort by CPU with P, memory with M
htop # More user-friendly (mouse support, color-coded, easier to kill processes)
kill: Terminate Processes
Stop a process with its PID (found via ps or top):
kill 1234 # Gracefully terminate process with PID 1234
kill -9 5678 # -9 (SIGKILL) force-kill unresponsive processes (last resort!)
pkill firefox # Kill all processes named "firefox" (no need for PID)
Background/Foreground Processes
Run commands in the background to free up the terminal. Use & to background a command:
long-running-task & # Run in background; returns PID (e.g., [1] 1234)
jobs # List background jobs (shows [1] Running)
fg %1 # Bring job 1 to foreground (use %jobnumber)
bg %1 # Send a stopped job back to background
6. Package Management
Install, update, and remove software via the command line. Package managers vary by Linux distribution:
Debian/Ubuntu (apt)
Debian-based systems (Ubuntu, Mint) use apt:
sudo apt update # Refresh package lists (always run first!)
sudo apt upgrade -y # Upgrade installed packages (-y auto-accepts prompts)
sudo apt install nginx # Install a package (e.g., web server nginx)
sudo apt remove firefox # Remove a package (keeps config files)
sudo apt purge firefox # Remove package AND config files
sudo apt autoremove # Remove unused dependencies
RHEL/CentOS/Fedora (dnf/yum)
Red Hat-based systems (Fedora, CentOS) use dnf (replaces yum):
sudo dnf check-update # List available updates
sudo dnf upgrade -y # Upgrade packages
sudo dnf install git # Install git
sudo dnf remove libreoffice # Remove a package
Universal Tools (snap/flatpak)
For apps not in official repos, use snap (Ubuntu) or flatpak (cross-distribution):
sudo snap install code # Install VS Code via snap
flatpak install flathub com.spotify.Client # Install Spotify via flatpak
7. Networking Essentials
Diagnose connectivity issues, transfer files, and access remote servers with these commands.
Check Network Status
View IP addresses, interfaces, and DNS:
ip addr # Show all network interfaces and IP addresses (replace ifconfig)
ping google.com # Test connectivity (Ctrl+C to stop)
nslookup github.com # Check DNS resolution (IP of github.com)
Download Files
Use curl or wget to download from URLs:
curl -O https://example.com/file.zip # -O saves with original filename
wget https://example.com/large.iso # Resume interrupted downloads with -c: wget -c URL
SSH: Remote Access
Securely connect to remote servers with ssh user@host:
ssh [email protected] # Connect to a local server
ssh -p 2222 [email protected] # Connect to port 2222 (default: 22)
ssh -i ~/.ssh/mykey.pem ec2-user@aws-instance # Use SSH key for authentication
8. Automation with Shell Scripts
Save time by automating repetitive tasks with shell scripts. A script is a text file with a sequence of commands.
Example: Backup Script
Create a script to back up files with rsync (a robust copying tool). Save as backup.sh:
#!/bin/bash
# Backup script for documents
SOURCE="/home/user/documents"
DEST="/mnt/external-drive/backups"
DATE=$(date +%Y-%m-%d) # Current date (e.g., 2024-09-10)
echo "Starting backup at $DATE..."
rsync -av --delete "$SOURCE" "$DEST/$DATE" # -a=archive (preserve permissions), -v=verbose
echo "Backup completed! Files saved to $DEST/$DATE"
Make it executable and run:
chmod +x backup.sh # Grant execute permission
./backup.sh # Run the script
Pro Tip: Add the script to cron (task scheduler) for automatic daily backups:
crontab -e # Edit cron jobs
# Add: 0 2 * * * /home/user/backup.sh # Run daily at 2 AM
9. Pro Tips & Productivity Hacks
Elevate your workflow with these time-savers:
Aliases
Create shortcuts for long commands. Add to ~/.bashrc (or ~/.zshrc) for permanence:
alias ll='ls -la' # ll = detailed list
alias upd='sudo apt update && sudo apt upgrade -y' # One command to update system
alias grep='grep --color=auto' # Colorize grep output
Reload the config with source ~/.bashrc.
History Navigation
Quickly reuse past commands:
history: List all past commands (with line numbers).!123: Run the 123rd command in history.Ctrl+R: Reverse search history (type a keyword to find a command).
Tab Completion
Press Tab to auto-complete filenames, commands, or flags. Double-tap Tab to see options:
cd Doc[Tab] # Completes to Documents if it exists
Command Chaining
Run multiple commands in one line:
command1 ; command2: Run command2 after command1 (regardless of success).command1 && command2: Run command2 only if command1 succeeds (e.g.,make && sudo make install).command1 || command2: Run command2 only if command1 fails.
10. Conclusion
The Linux command line is a skill that grows with practice. Start small: use ls, cd, and cp daily, then gradually add tools like grep or awk. Experiment with scripts, and don’t fear mistakes—even pros use man (manual pages) to look up commands (man grep for help with grep).
Remember: The best way to learn is by doing. Automate a task, troubleshoot a network issue, or write a script—each challenge will sharpen your skills.
11. References
- Man Pages: Type
man [command](e.g.,man ls) for official documentation. - Linux Documentation Project: Free guides and tutorials.
- Bash Handbook: A concise guide to Bash.
- Linux Journey: Interactive Linux learning platform.
- Book: The Linux Command Line by William Shotts (free online: linuxcommand.org/tlcl).
Happy coding! 🐧