Linux is the backbone of modern computing — powering servers, clouds, embedded devices, supercomputers, and even Android phones. Mastering the Linux terminal is the single most valuable skill for any developer, sysadmin, or DevOps engineer. This comprehensive course takes you from absolute beginner to command-line expert.

Table of Contents

  1. Introduction to Linux & the Terminal
  2. File System Navigation
  3. File & Directory Operations
  4. Viewing & Editing Files
  5. Text Processing Power Tools
  6. Permissions & Ownership
  7. Process Management
  8. Networking Commands
  9. Disk & Storage Management
  10. System Information & Monitoring
  11. Package Management
  12. Archives & Compression
  13. Searching & Finding Files
  14. Shell Scripting Basics
  15. Advanced Commands & Tips

1. Introduction to Linux & the Terminal

Linux is an open-source Unix-like operating system. The terminal (also called shell, command line, or CLI) is where you type commands to interact directly with the OS.

Opening the Terminal

  • Ubuntu/Debian: Ctrl+Alt+T
  • macOS: Cmd+Space → type “Terminal”
  • SSH (remote): Connect via ssh user@host

Basic Command Syntax

command [options] [arguments]

Example:

ls -la /home/user
  • ls = command (list directory)
  • -la = options (long format + show hidden files)
  • /home/user = argument (target directory)

Getting Help

man ls           # Manual page for ls command
ls --help        # Quick help summary
info ls          # Info documentation (more detailed)
whatis ls        # One-line description of the command
apropos keyword  # Search all man pages for keyword

Key Directories

/          # Root directory (top of the tree)
/bin       # Essential user binaries (commands)
/boot      # Boot loader files
/dev       # Device files (hardware)
/etc       # Configuration files
/home      # User home directories
/lib       # Shared libraries
/media     # Removable media mount points
/mnt       # Temporary mount points
/opt       # Optional/third-party software
/proc      # Virtual filesystem (process info)
/root      # Root user's home directory
/run       # Runtime variable data
/sbin      # System binaries
/srv       # Service data
/sys       # System information (virtual)
/tmp       # Temporary files
/usr       # User programs & data
/var       # Variable data (logs, databases)

Navigation Commands

pwd                    # Print working directory (where am I?)
ls                     # List files in current directory
ls -l                  # Long format (permissions, size, date)
ls -a                  # Show all files (including hidden .files)
ls -la                 # Long format + all files (most common)
ls -lh                 # Long format with human-readable sizes
ls -lt                 # Sort by modification time (newest first)
ls -ltr                # Sort by time, reversed (oldest first)
ls -R                  # Recursive listing (subdirectories too)
ls -d */               # List directories only

cd /path/to/dir        # Change directory
cd ~                   # Go to home directory
cd ~/Documents         # Go to Documents in home
cd -                   # Go to previous directory
cd ..                  # Go up one level
cd ../..               # Go up two levels
cd /                   # Go to root directory

tree                   # Show directory tree (install with apt)
tree -L 2              # Tree with max depth of 2 levels

3. File & Directory Operations

Creating & Removing

touch file.txt                # Create empty file (or update timestamp)
mkdir mydir                   # Create a directory
mkdir -p dir1/dir2/dir3       # Create nested directories (parent dirs too)
mkdir -m 755 newdir           # Create with specific permissions
rm file.txt                   # Delete a file (⚠️ permanent!)
rm -i file.txt                # Interactive (ask before delete)
rm -rf dir/                   # Delete directory + contents (⚠️ dangerous!)
rmdir emptydir                # Remove empty directory
rm -r dir/                    # Remove directory + contents

Copying & Moving

cp source.txt dest.txt                   # Copy file
cp -i source.txt dest.txt                # Interactive (ask before overwrite)
cp -r sourcedir/ destdir/                # Copy directory recursively
cp -a sourcedir/ destdir/                # Archive mode (preserve permissions, links)
cp -u source.txt dest.txt                # Copy only if source is newer
cp file1.txt file2.txt destdir/          # Copy multiple files to a directory

mv oldname.txt newname.txt               # Rename a file
mv file.txt /path/to/dest/               # Move file to another directory
mv -i file.txt dest/                     # Interactive move
mv -u file.txt dest/                     # Move only if source is newer
mv dir1/* dir2/                          # Move all files from dir1 to dir2

Links

ln -s target linkname           # Create a symbolic (soft) link
ln target linkname              # Create a hard link
ls -li                          # Show inode numbers to see hard links
readlink linkname               # Show where a symlink points

File Types & Info

file file.txt              # Determine file type
stat file.txt              # Detailed file statistics
wc -l file.txt             # Count lines in file
wc -w file.txt             # Count words
wc -c file.txt             # Count bytes
wc -m file.txt             # Count characters
du -sh file.txt            # Disk usage of a file
du -sh dir/                # Total disk usage of a directory
du -h --max-depth=1        # Disk usage per subdirectory

4. Viewing & Editing Files

cat file.txt                # Display entire file
cat file1.txt file2.txt     # Concatenate multiple files
tac file.txt                # Display file in reverse (line order)
nl file.txt                 # Display with line numbers

less file.txt               # Scroll through file (press q to quit)
more file.txt               # Page through file (older, less featured)

head file.txt               # Show first 10 lines
head -n 20 file.txt         # Show first 20 lines
head -c 100 file.txt        # Show first 100 bytes

tail file.txt               # Show last 10 lines
tail -n 20 file.txt         # Show last 20 lines
tail -f file.txt            # Follow file in real-time (logs!)
tail -f -n 100 file.txt     # Last 100 lines + follow

nano file.txt               # Simple terminal text editor
vim file.txt                # Powerful modal editor (use i to insert, Esc to stop)
echo "text" >> file.txt     # Append text to file
echo "text" > file.txt      # Overwrite file with text

5. Text Processing Power Tools

grep — Search Text

grep "pattern" file.txt                  # Search for pattern
grep -i "pattern" file.txt                # Case-insensitive search
grep -r "pattern" /path/                  # Recursive search
grep -v "pattern" file.txt                # Invert match (exclude pattern)
grep -n "pattern" file.txt                # Show line numbers
grep -c "pattern" file.txt                # Count matches
grep -l "pattern" *.txt                   # List filenames that match
grep -w "word" file.txt                   # Whole word match
grep -E "pat1|pat2" file.txt              # Extended regex (multiple patterns)
grep "^start" file.txt                    # Lines starting with "start"
grep "end$" file.txt                      # Lines ending with "end"
grep -A 3 "pattern" file.txt              # Show 3 lines After match
grep -B 3 "pattern" file.txt              # Show 3 lines Before match
grep -C 3 "pattern" file.txt              # Show 3 lines Context around match
ps aux | grep nginx                       # Find nginx processes
history | grep ssh                        # Search command history

sed — Stream Editor

sed 's/old/new/' file.txt                # Replace first occurrence per line
sed 's/old/new/g' file.txt               # Replace ALL occurrences per line
sed -i 's/old/new/g' file.txt            # Edit file in-place (⚠️ modifies original)
sed -i.bak 's/old/new/g' file.txt        # Edit in-place with backup
sed '/pattern/d' file.txt                # Delete lines matching pattern
sed -n '5,10p' file.txt                  # Print lines 5 to 10
sed '5d' file.txt                        # Delete line 5
sed 's/old/new/2' file.txt               # Replace 2nd occurrence per line
sed 's/^/PREFIX: /' file.txt             # Add prefix to each line
sed 's/$/ :SUFFIX/' file.txt             # Add suffix to each line

awk — Pattern Scanning & Processing

awk '{print $1}' file.txt                # Print first column (space-separated)
awk '{print $1, $3}' file.txt            # Print columns 1 and 3
awk -F',' '{print $1}' file.csv          # Use comma as field separator
awk '{sum+=$1} END {print sum}' nums.txt  # Sum of first column
awk 'NR==5' file.txt                     # Print line 5
awk '/pattern/' file.txt                 # Print lines matching pattern
awk 'length > 80' file.txt               # Print lines longer than 80 chars
awk '{print NR, $0}' file.txt            # Print with line numbers

sort & uniq

sort file.txt                            # Sort alphabetically
sort -n file.txt                         # Sort numerically
sort -r file.txt                         # Sort in reverse order
sort -k 2 file.txt                       # Sort by 2nd column
sort -u file.txt                         # Sort and remove duplicates
sort -h file.txt                         # Sort human-readable sizes (1K, 2G, etc.)

uniq file.txt                            # Remove adjacent duplicates (needs sorted input)
sort file.txt | uniq                     # Remove all duplicates
sort file.txt | uniq -c                  # Count occurrences
sort file.txt | uniq -d                  # Show only duplicates
sort file.txt | uniq -u                  # Show only unique lines

cut & paste

cut -d',' -f1,3 file.csv                # Cut fields 1 and 3 by comma delimiter
cut -c1-10 file.txt                      # Cut first 10 characters of each line
paste file1.txt file2.txt                # Merge files line by line
paste -d',' file1.txt file2.txt          # Merge with comma delimiter

tr — Translate Characters

echo "hello" | tr 'a-z' 'A-Z'           # Convert to uppercase
echo "HELLO" | tr 'A-Z' 'a-z'           # Convert to lowercase
cat file.txt | tr -d '\n'               # Delete all newlines
cat file.txt | tr -s ' '                 # Squeeze multiple spaces to one

diff & comm

diff file1.txt file2.txt                 # Show differences line by line
diff -u file1.txt file2.txt              # Unified diff format
diff -r dir1/ dir2/                      # Compare directories recursively
sdiff file1.txt file2.txt                # Side-by-side comparison
comm file1.txt file2.txt                 # Compare sorted files (common/unique lines)

vimdiff file1.txt file2.txt              # Visual diff in vim

6. Permissions & Ownership

Understanding Permissions

ls -l file.txt
# Output: -rwxr-xr-- 1 user group 1024 May 31 10:00 file.txt
#          ^^^^ ^^^ ^^^
#          |    |   |
#          |    |   +-- Others permissions (r--)
#          |    +------ Group permissions (r-x)
#          +----------- Owner permissions (rwx)
#          ^----------- File type (-=file, d=directory, l=link)

Permission Codes

r = 4 = read
w = 2 = write
x = 1 = execute
--- = 0 = no permissions

chmod 755 file.txt       # rwxr-xr-x (owner=all, group=rx, others=rx)
chmod 644 file.txt       # rw-r--r-- (owner=rw, group=r, others=r)
chmod 600 file.txt       # rw------- (owner=rw only)
chmod 777 file.txt       # rwxrwxrwx (everyone=all, ⚠️ insecure)
chmod 400 file.txt       # r-------- (read only for owner)

Symbolic Permissions

chmod u+x file.txt          # Add execute for owner (user)
chmod g+w file.txt          # Add write for group
chmod o-r file.txt          # Remove read for others
chmod a+x file.txt          # Add execute for all (user+group+others)
chmod u=rwx,g=rx,o=r file   # Exact permissions (same as 755)
chmod -R 755 dir/           # Recursive (all files and subdirs)

Ownership

chown user file.txt                    # Change owner
chown user:group file.txt              # Change owner and group
chown :group file.txt                  # Change group only
chown -R user:group dir/               # Recursive ownership change
chgrp group file.txt                   # Change group only

Special Permissions

chmod u+s file.txt          # SUID (run as file owner, not caller)
chmod g+s dir/              # SGID (new files inherit group)
chmod o+t dir/              # Sticky bit (only owner can delete files)
ls -l                       # SUID = 's' in owner x, SGID = 's' in group x, Sticky = 't' in others x

# Examples
chmod 4755 file.txt         # rwsr-xr-x (SUID + 755)
chmod 2755 dir/             # rwxr-sr-x (SGID + 755)
chmod 1777 /tmp             # rwxrwxrwt (sticky bit, /tmp is 1777)

Umask — Default Permissions

umask                      # Show current umask (e.g., 0022)
umask 0022                 # Default: files 644, dirs 755
umask 0077                 # Default: files 600, dirs 700
umask 0002                 # Default: files 664, dirs 775 (for groups)

7. Process Management

ps                         # Show your processes in current terminal
ps aux                     # Show ALL processes (most common)
ps aux --sort=-%mem        # Sort by memory usage (highest first)
ps aux --sort=-%cpu        # Sort by CPU usage
ps -ef                     # Full format listing
ps -u username             # Processes for a specific user
ps -p PID                  # Info about specific process
ps -Lf PID                 # Show threads of a process
pstree                     # Process tree (hierarchical view)

top                        # Live process monitor (press q to quit)
htop                       # Enhanced top (install with apt install htop)

kill PID                   # Gracefully terminate process (SIGTERM)
kill -9 PID                # Force kill (SIGKILL, ⚠️ doesn't save data)
kill -15 PID               # SIGTERM (same as kill without flag)
kill -1 PID                # SIGHUP (reload configuration)
killall process_name       # Kill all processes by name
pkill process_name         # Kill process by name pattern
pgrep process_name         # Find PID by process name

nice -n 10 command         # Run command with lower priority
renice -n 5 -p PID         # Change priority of running process
renice -n -5 -p PID        # Higher priority (negative = higher, needs root)

nohup command &            # Run command immune to hangups
command &                  # Run in background (returns to shell)
jobs                       # List background jobs
fg %1                      # Bring job 1 to foreground
bg %1                      # Resume job 1 in background
ctrl+z                     # Suspend current process (background it)

watch -n 2 command         # Run command every 2 seconds (live updates)
watch -d command           # Highlight differences between updates
watch 'ps aux | grep httpd' # Monitor specific processes

Systemd (modern init system)

systemctl status nginx           # Check service status
systemctl start nginx             # Start a service
systemctl stop nginx              # Stop a service
systemctl restart nginx           # Restart a service
systemctl reload nginx            # Reload config (no downtime)
systemctl enable nginx            # Enable service at boot
systemctl disable nginx           # Disable service at boot
systemctl list-units --type=service  # List all services
journalctl -u nginx               # View logs for a service
journalctl -u nginx -f            # Follow logs in real-time
journalctl --since "1 hour ago"   # Logs from last hour

8. Networking Commands

Connection & Diagnostics

ping google.com                  # Test connectivity to host
ping -c 4 google.com             # Send 4 pings and stop
ping -i 2 google.com             # Ping every 2 seconds

curl https://example.com          # Fetch URL (HTTP/HTTPS)
curl -O https://example.com/file  # Download file (save with original name)
curl -L https://bit.ly/short      # Follow redirects
curl -I https://example.com       # Fetch only HTTP headers
curl -d "key=value" -X POST URL   # Send POST request
curl -H "Authorization: Bearer token" URL   # Custom header

wget https://example.com/file     # Download file
wget -c https://example.com/file  # Resume interrupted download
wget -r https://example.com/      # Recursive download (mirror site)
wget -q https://example.com/file  # Quiet mode (no output)

Network Info

ip a                           # Show all network interfaces (modern)
ip addr                        # Same as ip a
ip link                        # Show link layer interfaces
ip route                       # Show routing table
ip neigh                       # Show ARP cache (neighbors)

ifconfig                       # Show network interfaces (older, may need net-tools)
route -n                       # Show routing table (older)

ss -tuln                       # Show listening ports (modern replacement for netstat)
ss -tup                        # Show all TCP/UDP connections with processes
ss -lntp                       # TCP listening with PID/program name

netstat -tuln                  # Show listening ports (older)
netstat -tup                   # Show connections with processes
netstat -rn                    # Show routing table

DNS & Domain

nslookup example.com           # DNS lookup (simple)
dig example.com                # Detailed DNS query
dig example.com MX             # Get mail exchange records
dig example.com ANY            # Get all record types
host example.com               # Simple DNS lookup
whois example.com              # Domain registration info (may need whois package)

SSH — Secure Shell

ssh user@host                  # Connect to remote server
ssh -p 2222 user@host          # Connect on non-standard port
ssh -i key.pem user@host       # Connect with private key
ssh -J jumpuser@jump host      # Jump host / bastion (ProxyJump)
ssh-copy-id user@host          # Copy SSH key to server (passwordless login)
scp file.txt user@host:/dest/  # Copy file via SSH
scp -r dir/ user@host:/dest/   # Copy directory recursively
rsync -avz src/ user@host:/dest/   # Sync directory (efficient, resume-capable)
sftp user@host                 # FTP-like file transfer over SSH

9. Disk & Storage Management

df -h                          # Show disk usage (human-readable)
df -hT                         # Show filesystem type too
df -i                          # Show inode usage (not space)
du -sh /home/*                 # Disk usage per user
du -h --max-depth=1            # Disk usage per directory (one level)

lsblk                          # List block devices (disks, partitions)
lsblk -f                       # Show filesystem info
fdisk -l                       # Partition table (needs root)
blkid                          # Show UUID and filesystem type
mount                          # Show mounted filesystems
mount /dev/sdb1 /mnt/usb       # Mount a device
umount /mnt/usb                # Unmount a device

fsck /dev/sda1                 # Check filesystem integrity (unmount first!)
dd if=/dev/sda of=backup.img bs=4M   # Create disk image (⚠️ careful with dd!)
dd if=/dev/zero of=file bs=1M count=100    # Create 100MB test file

findmnt                        # Show mount tree
findmnt -T /path               # Find which filesystem a path is on

10. System Information & Monitoring

uname -a                       # All system info (kernel, architecture)
uname -r                       # Kernel version
hostname                       # System hostname
hostname -I                    # Show IP addresses

uptime                         # How long system has been running
who                            # Who is logged in
w                              # Who is logged in + what they're doing
last                           # Last logins
lastb                          # Last failed logins
lastlog                        # Last login of all users

free -h                        # Memory usage (human-readable)
free -m                        # Memory in MB
free -h -s 5                   # Memory every 5 seconds

lscpu                          # CPU information
lspci                          # PCI devices
lsusb                          # USB devices
lshw                           # Hardware info (needs root/apt install)
dmidecode                      # BIOS/System info (needs root)
lsmod                          # Loaded kernel modules
modinfo module_name            # Information about a kernel module

dmesg                          # Kernel ring buffer messages (boot logs)
dmesg -w                       # Follow kernel messages in real-time
dmesg | tail -20               # Last 20 kernel messages

bat /sys/class/thermal/thermal_zone*/temp  # CPU temperature (millidegrees)

vmstat 2                       # Virtual memory stats every 2 seconds
iostat 2                       # I/O stats every 2 seconds (needs sysstat)
mpstat 2                       # Per-processor stats (needs sysstat)

11. Package Management

Debian/Ubuntu (APT)

apt update                     # Update package list
apt upgrade                    # Upgrade all packages
apt full-upgrade               # Upgrade with dependency resolution
apt install package            # Install a package
apt install -y package         # Install without confirmation
apt remove package             # Remove a package (keep config files)
apt purge package              # Fully remove (including config)
apt autoremove                 # Remove unused dependencies
apt list --installed           # List installed packages
apt search keyword             # Search for packages
apt show package               # Show package details
dpkg -i package.deb            # Install local .deb file
dpkg -l                        # List installed packages (older)
dpkg -L package                # List files installed by a package

Red Hat/Fedora (DNF)

dnf install package            # Install a package
dnf update                     # Update all packages
dnf remove package             # Remove a package
dnf search keyword             # Search for packages
dnf list installed             # List installed packages
dnf info package               # Show package details

RHEL/CentOS (YUM — older)

yum install package            # Install a package
yum update                     # Update all packages
yum remove package             # Remove a package
yum search keyword             # Search packages
yum list installed             # List installed packages
rpm -ivh package.rpm           # Install local .rpm file
rpm -qa                        # List all installed RPMs

Arch Linux (Pacman)

pacman -S package              # Install a package
pacman -Syu                    # Full system update
pacman -R package              # Remove a package
pacman -Qs keyword             # Search for packages
pacman -Q                      # List installed packages

Snap & Flatpak

snap install package           # Install via Snap
snap list                      # List installed snaps
snap remove package            # Remove a snap

flatpak install package        # Install via Flatpak
flatpak list                   # List installed flatpaks
flatpak uninstall package      # Remove a flatpak

12. Archives & Compression

tar — Tape Archive

tar -cf archive.tar files/     # Create tar archive
tar -xf archive.tar            # Extract tar archive
tar -tf archive.tar            # List contents of tar archive
tar -czf archive.tar.gz dir/   # Create gzipped tar
tar -xzf archive.tar.gz        # Extract gzipped tar
tar -cjf archive.tar.bz2 dir/  # Create bzipped tar (better compression)
tar -xjf archive.tar.bz2       # Extract bzipped tar
tar -cJf archive.tar.xz dir/   # Create xz tar (best compression)
tar -xJf archive.tar.xz        # Extract xz tar
tar -xzf archive.tar.gz -C /target/dir   # Extract to specific directory
tar -czf archive.tar.gz --exclude='*.log' dir/    # Exclude files matching pattern

gzip, bzip2, xz

gzip file.txt                  # Compress (file.txt → file.txt.gz)
gunzip file.txt.gz             # Decompress
gzip -k file.txt               # Compress, keep original (v1.6+)
gzip -l file.txt.gz            # Show compression info
gzip -r dir/                   # Compress all files in directory
gzip -d file.txt.gz            # Decompress (same as gunzip)

bzip2 file.txt                 # Compress (better ratio, slower)
bunzip2 file.txt.bz2           # Decompress
xz file.txt                    # Compress (best ratio)
unxz file.txt.xz               # Decompress

zip

zip archive.zip file1 file2    # Create zip archive
zip -r archive.zip dir/        # Recursively zip a directory
unzip archive.zip              # Extract zip archive
unzip -l archive.zip           # List contents without extracting
unzip archive.zip -d /dest/    # Extract to specific directory
zip -9 archive.zip file        # Maximum compression
zip -e archive.zip file        # Encrypt with password
find /path -name "*.txt"               # Find files by name
find /path -iname "*.TXT"              # Case-insensitive name search
find /path -type f                     # Find files only
find /path -type d                     # Find directories only
find /path -size +100M                 # Files larger than 100MB
find /path -size -1k                   # Files smaller than 1KB
find /path -mtime -7                   # Modified in last 7 days
find /path -mtime +30                  # Modified more than 30 days ago
find /path -amin -60                   # Accessed in last 60 minutes
find /path -user username              # Files owned by user
find /path -perm 644                   # Files with specific permissions
find /path -empty                      # Empty files and directories
find /path -name "*.log" -delete       # Find and delete
find /path -name "*.tmp" -exec rm {} \;  # Execute command on findings
find /path -name "*.jpg" -exec cp {} /backup/ \;  # Copy found files
find /path -maxdepth 2 -name "*.txt"   # Limit search depth
find /path -name "*.txt" | xargs grep "pattern"   # Find files then search in them

locate file.txt                  # Find file by name (uses database, very fast)
sudo updatedb                    # Update locate database (run periodically)
which command                    # Show path of a command (e.g., which python3)
whereis command                  # Show binary, source, and man page locations
type command                     # Show how command is interpreted (alias, built-in, path)

14. Shell Scripting Basics

Creating a Script

#!/bin/bash
# This is a comment
echo "Hello, World!"
  1. Save as myscript.sh
  2. Make executable: chmod +x myscript.sh
  3. Run: ./myscript.sh or bash myscript.sh

Variables

#!/bin/bash
name="John"
echo "Hello, $name"
echo "Hello, ${name}"       # Same (bracing for clarity)
echo "Script: $0"            # Script name
echo "First arg: $1"         # First argument
echo "All args: $@"          # All arguments
echo "Arg count: $#"         # Number of arguments
echo "Exit code: $?"         # Last command's exit status
echo "PID: $$"               # Current script PID

Conditionals

#!/bin/bash
if [ "$1" = "hello" ]; then
    echo "Hi there!"
elif [ "$1" = "bye" ]; then
    echo "See you!"
else
    echo "I don't understand"
fi

# File tests
if [ -f "$file" ]; then      # Is it a file?
if [ -d "$dir" ]; then       # Is it a directory?
if [ -e "$path" ]; then      # Does it exist?
if [ -s "$file" ]; then      # Is file non-empty?
if [ -r "$file" ]; then      # Is file readable?
if [ -w "$file" ]; then      # Is file writable?
if [ -x "$file" ]; then      # Is file executable?

# String tests
if [ -z "$str" ]; then       # Is string empty?
if [ -n "$str" ]; then       # Is string non-empty?
if [ "$a" = "$b" ]; then     # Strings equal
if [ "$a" != "$b" ]; then    # Strings not equal

# Numeric comparisons
if [ "$a" -eq "$b" ]; then   # Equal
if [ "$a" -ne "$b" ]; then   # Not equal
if [ "$a" -gt "$b" ]; then   # Greater than
if [ "$a" -lt "$b" ]; then   # Less than
if [ "$a" -ge "$b" ]; then   # Greater or equal
if [ "$a" -le "$b" ]; then   # Less or equal

Loops

#!/bin/bash
# For loop
for i in 1 2 3 4 5; do
    echo "Number: $i"
done

for file in *.txt; do
    echo "Processing: $file"
done

for i in {1..10}; do          # Range (bash 4+)
    echo "$i"
done

# While loop
count=1
while [ "$count" -le 5 ]; do
    echo "Count: $count"
    ((count++))
done

# Read file line by line
while IFS= read -r line; do
    echo "$line"
done < file.txt

Functions

#!/bin/bash
greet() {
    echo "Hello, $1!"
}

greet "World"                # Output: Hello, World!

# Return values
add() {
    return $(($1 + $2))
}
add 3 4
echo "Result: $?"            # Output: Result: 7

Useful One-Liners

# Backup a directory with timestamp
tar -czf backup-$(date +%Y%m%d_%H%M%S).tar.gz /path/to/dir

# Find and replace text in multiple files
sed -i 's/oldtext/newtext/g' *.txt

# Monitor a log file and send alerts
tail -f /var/log/syslog | grep --line-buffered "ERROR" | while read line; do
    echo "$line" | mail -s "Alert" admin@example.com
done

# Batch rename files
for f in *.JPG; do mv "$f" "${f%.JPG}.jpg"; done

# Count total lines of code
find . -name "*.py" | xargs wc -l | tail -1

15. Advanced Commands & Tips

Input/Output Redirection

command > file.txt            # Redirect stdout to file (overwrite)
command >> file.txt           # Redirect stdout to file (append)
command 2> error.txt          # Redirect stderr to file
command &> file.txt           # Redirect both stdout and stderr
command > /dev/null           # Discard output (send to null device)
command 2>&1                  # Merge stderr into stdout
command | tee file.txt        # Output to both screen and file
command | tee -a file.txt     # Append to file while showing on screen

Job Control

command &                     # Run in background
ctrl+z                        # Suspend current process (pause)
jobs                          # List background/suspended jobs
bg %1                         # Resume job 1 in background
fg %1                         # Resume job 1 in foreground
kill %1                       # Kill background job 1
disown %1                     # Remove job from shell's job table

Environment Variables

echo $PATH                    # Show executable search paths
echo $HOME                    # Show home directory
echo $USER                    # Current username
echo $SHELL                   # Current shell
env                           # Show all environment variables
export VAR="value"            # Set environment variable (persists for child processes)
export PATH=$PATH:/new/path   # Add directory to PATH

# Profile files
~/.bashrc                     # Run on each interactive bash session
~/.bash_profile               # Run on login (macOS)
~/.profile                    # Run on login (Linux)
~/.bash_logout                # Run on logout
/etc/bash.bashrc              # System-wide bashrc
/etc/profile                  # System-wide profile

Aliases

alias ll='ls -la'                      # Create alias
alias gs='git status'                  # Git shortcuts
alias ..='cd ..'                       # Go up
alias ...='cd ../..'                   # Go up two levels
alias df='df -h'                       # Human-readable df
alias du='du -h'                       # Human-readable du
alias grep='grep --color=auto'         # Colored grep
alias rm='rm -i'                       # Interactive rm (safety!)
unalias ll                             # Remove alias

History

history                       # Show command history
history | grep ssh            # Find previous SSH commands
!!                            # Run the last command
!$                            # Last argument of previous command
!100                          # Run command #100 from history
!string                       # Run most recent command starting with 'string'
ctrl+r                        # Search backward through history (interactive)
ctrl+s                        # Search forward through history
fc -l                         # List recent commands (for editing)

Process Substitution

diff <(sort file1.txt) <(sort file2.txt)    # Compare sorted files
while read line; do echo "$line"; done < <(command)   # Feed output of command to loop

Useful Shortcuts

ctrl+a         # Go to beginning of line
ctrl+e         # Go to end of line
ctrl+u         # Cut from cursor to beginning
ctrl+k         # Cut from cursor to end
ctrl+y         # Paste cut text
ctrl+w         # Cut one word backward
ctrl+left      # Move one word left
ctrl+right     # Move one word right
ctrl+l         # Clear screen (same as clear)
ctrl+d         # Exit shell or EOF
ctrl+c         # Interrupt current process
ctrl+z         # Suspend current process
ctrl+r         # Search history
ctrl+s         # Pause output / forward search
ctrl+q         # Resume output
tab            # Auto-complete
tab tab        # Show all completions

Essential .bashrc Additions

# Add to ~/.bashrc for a better terminal experience:
export EDITOR=nano
export HISTSIZE=10000
export HISTFILESIZE=20000
export HISTCONTROL=ignoredups:erasedups
shopt -s histappend
shopt -s checkwinsize

# Git branch in prompt
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h:\w\$(parse_git_branch)\$ "

System Rescue & Recovery

sudo !!                       # Run last command as root
sudo -i                       # Root shell
sudo -s                       # Root shell (preserves env)
su - username                 # Switch to another user
passwd                        # Change your password
passwd username               # Change another user's password (root)

shutdown -h now               # Shutdown immediately
shutdown -r now               # Reboot immediately
shutdown -r +5                # Reboot in 5 minutes
shutdown -c                   # Cancel scheduled shutdown
reboot                        # Reboot
poweroff                      # Power off
halt                          # Halt the system
init 0                        # Shutdown (runlevel 0)
init 6                        # Reboot (runlevel 6)

Security Basics

# SSH key management
ssh-keygen -t ed25519         # Generate SSH key (modern, secure)
ssh-keygen -t rsa -b 4096     # Generate RSA key (compatible)
ssh-copy-id user@host         # Copy public key to server

# File integrity
md5sum file.txt               # MD5 checksum
sha256sum file.txt            # SHA-256 checksum
sha1sum file.txt              # SHA-1 checksum

# Encrypt/Decrypt
gpg -c file.txt               # Symmetric encryption (prompts for password)
gpg -d file.txt.gpg           # Decrypt
openssl enc -aes-256-cbc -salt -in file.txt -out file.enc   # OpenSSL encryption

Performance Troubleshooting

# Quick system health check
uptime                        # Load averages
free -h                       # Memory
df -h                         # Disk space
top -bn1 | head -5            # Top processes (one shot)
dmesg | tail                   # Recent kernel messages
journalctl -p err -b          # Error-level logs from current boot

# Network troubleshooting
ping -c 4 google.com          # Basic connectivity
traceroute google.com         # Trace network path
mtr google.com                # Combined ping + traceroute (live)
nslookup example.com          # DNS resolution
curl -I https://example.com   # HTTP header check
ss -tuln                      # What ports are listening?

Most Used Commands Cheat Sheet

# File Operations
ls -la          # List all files
cp -r src dest  # Copy directory
mv src dest     # Move/rename
rm -rf dir/     # Delete directory
mkdir -p a/b/c  # Create nested dirs

# Viewing
cat file        # Full file
less file       # Scrollable
tail -f file    # Follow log file

# Text Processing
grep -r "pat" . # Search recursively
sed -i 's/a/b/g' file   # Replace in file
awk '{print $1}' file   # Print first column
sort | uniq -c  # Count occurrences

# Permissions
chmod 755 file  # rwxr-xr-x
chown user:group file

# Process
ps aux          # All processes
kill -9 PID     # Force kill

# Network
curl URL        # HTTP request
ssh user@host   # Remote connection
scp file host:/path  # Copy over SSH

# System
df -h           # Disk space
free -h         # Memory
uname -a        # System info

Conclusion

Mastering the Linux command line is a superpower. Every command you learn removes friction — you stop clicking through GUIs and start thinking in operations. The terminal is faster, more powerful, and infinitely scriptable.

Practice tips:

  • Use Linux as your daily driver (try Ubuntu or Fedora)
  • Set up a home server to practice sysadmin tasks
  • Write shell scripts for repetitive tasks
  • Read command manuals (man command) regularly
  • Challenge yourself: automate something every day

Next steps:

  • Learn vim or emacs for terminal-based editing
  • Master git for version control
  • Learn docker and containerization
  • Study awk and sed deeply (they're entire languages)
  • Set up ansible for configuration management

Remember: The man pages are your best friend. Every command's manual has examples, options, and explanations. man command is the first thing to try when you're stuck.

More Free Courses on TricksPage

  • Git & GitHub Course — Master Git from basics to collaboration workflows, CI/CD, and open-source.
  • Linux Commands Course — Complete Linux command line mastery — navigation, text processing, scripting, networking.
  • Docker & Swarm Course — Containers, Dockerfiles, Compose, Swarm orchestration, and production deployment.
  • n8n Automation Course — Workflow automation with 400+ integrations, webhooks, AI, and error handling.
  • Agentic AI Course — Build AI agents with ReAct patterns, tools, memory, and multi-agent orchestration.

Leave a Reply

Your email address will not be published. Required fields are marked *