Comprehensive Linux Documentation

Complete Linux Guide

From ls and cd to kernel modules and container orchestration. This documentation covers everything you need to master Linux — with practical examples, deep explanations, and best practices from official documentation.

1 Introduction to Linux

What is Linux and why should you learn it?

Linux is a Unix-like, open-source operating system kernel first released by Linus Torvalds in 1991. Built on the principles of portability, multi-user support, and security, Linux has grown into the backbone of modern computing infrastructure — powering servers, cloud platforms, supercomputers, embedded systems, and mobile devices (via Android).

Key Features

  • Open Source: Full source code available under the GPL license — free to use, modify, and distribute
  • Multi-user & Multi-tasking: Multiple users and processes run simultaneously without interference
  • Security: Robust permission system, SELinux/AppArmor, and regular security patches
  • Stability: Uptimes measured in years; the kernel rarely crashes
  • Portability: Runs on x86, ARM, RISC-V, and virtually every hardware architecture
  • Modular Design: Loadable kernel modules (LKMs) extend functionality without rebooting

Main Applications

DomainKey TechnologiesExample
Web ServersNginx, Apache, CaddyGoogle, Facebook, Netflix
Cloud & DevOpsDocker, Kubernetes, AnsibleAWS, Azure, GCP infrastructure
SupercomputingMPI, OpenMP, SLURMTop 500 supercomputers (100% run Linux)
Embedded & IoTBuildroot, Yocto, OpenWrtRouters, smart TVs, Tesla cars
MobileAndroid (Linux kernel)3+ billion active devices
Note: Linux refers specifically to the kernel. What most people call "Linux" is technically GNU/Linux — the kernel combined with GNU tools and utilities.

2 Linux Distributions

Choosing the right distro for your needs

A Linux distribution (distro) is an operating system made from the Linux kernel plus a collection of software packages, package manager, and often a desktop environment. Different distros target different use cases — from servers to desktops to embedded systems.

Major Distribution Families

FamilyPackage ManagerPopular DistrosBest For
Debianapt, dpkgDebian, Ubuntu, Linux Mint, Pop!_OSServers, desktops, beginners
Red Hatdnf, rpmFedora, RHEL, CentOS Stream, AlmaLinux, Rocky LinuxEnterprise servers, workstations
ArchpacmanArch Linux, Manjaro, EndeavourOSPower users, rolling release
SUSEzypperopenSUSE, SUSE Linux EnterpriseEnterprise, YaST administration
GentooPortageGentoo, ChromeOSSource-based, maximum control
AlpineapkAlpine LinuxContainers, minimal footprint

Release Models

  • Fixed Release: Major versions released on a schedule (e.g., Ubuntu 24.04 LTS, RHEL 9). Stable and predictable.
  • Rolling Release: Continuous updates (e.g., Arch, openSUSE Tumbleweed). Always up-to-date but requires more maintenance.
  • Long-Term Support (LTS): Extended security updates (5+ years). Ideal for production servers.
Recommendation: Start with Ubuntu LTS or Linux Mint for desktops. Use Debian or AlmaLinux/Rocky for servers. Try Alpine for Docker containers.

3 Terminal Basics

Mastering the command line interface

The terminal (or shell) is the primary interface for interacting with Linux. Unlike graphical interfaces, the command line offers precision, automation, and remote administration capabilities that are essential for system administration.

Common Shells

ShellPathDescription
bash/bin/bashBourne Again SHell — default on most distros
zsh/bin/zshZ Shell — powerful scripting, popular with developers
fish/usr/bin/fishFriendly Interactive SHell — auto-suggestions, colors
sh/bin/shPOSIX-compliant shell — portable scripts

Basic Terminal Commands

bash
clear

Clears everything currently shown in the terminal window and gives you a blank screen.

bash
history

Shows a numbered list of the commands you've previously run in this shell.

bash
history | grep "apt"

Searches your command history for lines that mention "apt" — handy for finding a command you ran a while ago.

bash
!42

Re-runs command number 42 from your history, exactly as it was typed the first time.

bash
echo $SHELL

Prints the path of your default login shell (e.g. /bin/bash).

bash
echo $0

Prints the name of the shell that is actually running right now, which is useful when $SHELL doesn't match reality.

Tab completion also speeds things up: press TAB once to auto-complete commands, files, and directory names, or press it twice in a row to list every possible completion.

Keyboard Shortcuts

  • Ctrl+C Interrupts (kills) the process currently running in the foreground.
  • Ctrl+D Exits the shell by sending an end-of-file (EOF) signal.
  • Ctrl+L Clears the screen — the keyboard equivalent of running clear.
  • Ctrl+A Moves the cursor to the beginning of the current line.
  • Ctrl+E Moves the cursor to the end of the current line.
  • Ctrl+U Clears the line from the cursor back to the beginning.
  • Ctrl+K Clears the line from the cursor to the end.
  • Ctrl+R Starts a reverse search through your command history.
  • Ctrl+Z Suspends the foreground process, sending it to the background.

Getting Help

Manual pages - the most comprehensive documentation.

bash
man ls

Manual for 'ls' command.

bash
man -k "search"

Search man pages by keyword.

bash
man 5 passwd

Section 5: file formats.

Brief description.

bash
whatis ls
bash
apropos "copy"

Search for commands by description.

Built-in help.

bash
ls --help
bash
help cd

Help for bash built-ins.

Info pages (more detailed than man)

bash
info coreutils
bash
info bash

4 File System Hierarchy

Understanding the Linux directory structure

Linux follows the Filesystem Hierarchy Standard (FHS), which defines the directory structure and its contents. Understanding this hierarchy is fundamental to navigation and system administration.

DirectoryPurpose
/Root directory — the top of the filesystem tree
/binEssential user command binaries (ls, cp, mv)
/sbinSystem administration binaries (fdisk, mkfs)
/etcSystem-wide configuration files
/homeUser home directories
/rootHome directory for root user
/varVariable data — logs, caches, spool files
/tmpTemporary files (cleared on reboot)
/usrUser programs, libraries, documentation
/usr/binNon-essential user binaries
/usr/localLocally installed software
/optOptional application software packages
/devDevice files (disks, terminals, null)
/procVirtual filesystem for process/kernel info
/sysVirtual filesystem for system/hardware info
/mntTemporary mount point for filesystems
/mediaMount point for removable media (USB, CD)
/bootBoot loader files (kernel, initramfs)
/libEssential shared libraries
/srvData for services (web, FTP)
Key Principle: Everything in Linux is a file — directories, devices, processes, even network sockets. This unified abstraction is one of Linux's most powerful design decisions.

6 File Operations

Creating, copying, moving, and deleting files

Create files.

bash
touch file.txt

Create empty file or update timestamp.

bash
touch {a,b,c}.txt

Create multiple files.

bash
echo "Hello" > file.txt

Create with content (overwrite)

bash
echo "World" >> file.txt

Append to file.

Copy files and directories.

bash
cp file.txt backup.txt

Copy file.

bash
cp -r dir1/ dir2/

Recursive copy (directories)

bash
cp -i file.txt dest/

Interactive (prompt before overwrite)

bash
cp -v file.txt dest/

Verbose.

bash
cp -a source/ dest/

Archive mode (preserve permissions, links)

Move and rename.

bash
mv old.txt new.txt

Rename.

bash
mv file.txt /tmp/

Move to directory.

bash
mv -i file.txt dest/

Interactive.

Delete files and directories.

bash
rm file.txt

Remove file.

bash
rm -i file.txt

Interactive.

bash
rm -f file.txt

Force (no prompt)

bash
rm -r directory/

Remove directory recursively.

bash
rm -rf directory/

Force recursive (DANGEROUS!)

Create directories.

bash
mkdir newdir

Create directory.

bash
mkdir -p path/to/nested

Create nested directories.

Remove empty directories.

bash
rmdir emptydir

Remove empty directory.

bash
rmdir -p a/b/c

Remove nested empty directories.

Create links.

bash
ln file.txt hardlink

Hard link (same inode)

bash
ln -s file.txt symlink

Symbolic link (shortcut)

bash
ln -s /var/log/logs logs

Symlink to directory.

Warning: rm -rf / will recursively delete your entire filesystem. Always double-check your commands, especially when using wildcards with rm.

7 File Permissions

Understanding and managing access control

Linux uses a permission-based access control system that determines who can read, write, or execute files and directories. Every file has an owner, a group, and permissions for three categories: owner, group, and others.

Permission Notation

PermissionNumericSymbolicEffect on FileEffect on Directory
Read4rView contentsList files
Write2wModify contentsCreate/delete files
Execute1xRun as programEnter directory

chmod - Change Permissions

Numeric mode (owner, group, others)

bash
chmod 755 script.sh

Rwxr-xr-x.

bash
chmod 644 file.txt

Rw-r--r--.

bash
chmod 700 private.key

Rwx------ (only owner)

bash
chmod 777 shared/

Rwxrwxrwx (everyone)

Symbolic mode.

bash
chmod u+x script.sh

Add execute for owner.

bash
chmod go-w file.txt

Remove write for group and others.

bash
chmod a=r file.txt

Set read-only for all.

bash
chmod u=rwx,g=rx,o= file

Set specific permissions.

Recursive.

bash
chmod -R 755 directory/

Apply to all files and subdirectories.

Special permissions.

bash
chmod 4755 program

SUID - run as file owner.

bash
chmod 2755 directory

SGID - new files inherit group.

bash
chmod 1755 /tmp

Sticky bit - only owner can delete.

Default Permissions with umask

Check current umask.

bash
umask

0022 (typical default)

Calculate default permissions:

Files: 666 - umask = 644 (rw-r--r--)

Directories: 777 - umask = 755 (rwxr-xr-x)

Set umask (restrictive)

bash
umask 027

Files: 640, Directories: 750.

Make umask persistent.

bash
echo "umask 027" >> ~/.bashrc

8 Ownership & ACL

Managing who owns what, beyond basic permissions

Every file and directory in Linux belongs to a user owner and a group owner. Standard permission bits (owner/group/others) are often not granular enough — Access Control Lists (ACLs) extend this model to allow permissions for specific additional users or groups.

Changing Ownership

Change owner.

bash
chown alice file.txt

Set user owner.

bash
chown alice:staff file.txt

Set user and group.

bash
chown :staff file.txt

Set group only.

bash
chown -R alice:staff dir/

Recursive.

Change group only.

bash
chgrp developers file.txt

Reference another file's ownership.

bash
chown --reference=ref.txt file.txt

Access Control Lists (ACL)

View ACLs.

bash
getfacl file.txt

Grant a specific user read/write access.

bash
setfacl -m u:bob:rw file.txt

Grant a group execute access.

bash
setfacl -m g:interns:rx script.sh

Set default ACL for a directory (inherited by new files)

bash
setfacl -d -m u:bob:rwx project/

Remove a specific entry.

bash
setfacl -x u:bob file.txt

Remove all ACL entries.

bash
setfacl -b file.txt
Note: When a file has extra ACL entries, ls -l shows a + after the permission string, e.g. -rw-rw-r--+.

9 Archiving & Compression

Bundling and shrinking files for storage or transfer

Linux separates archiving (combining multiple files into one) from compression (reducing size). The tar utility handles archiving and can pipe through a compressor in the same command.

tar - Tape Archive

Create archive.

bash
tar -cvf archive.tar dir/

C=create v=verbose f=file.

bash
tar -czvf archive.tar.gz dir/

Gzip compression.

bash
tar -cjvf archive.tar.bz2 dir/

Bzip2 (better ratio, slower)

bash
tar -cJvf archive.tar.xz dir/

Xz (best ratio, slowest)

Extract archive.

bash
tar -xvf archive.tar
bash
tar -xzvf archive.tar.gz
bash
tar -xvf archive.tar -C /target/dir/

Extract to specific dir.

List contents without extracting.

bash
tar -tvf archive.tar

Extract a single file.

bash
tar -xvf archive.tar path/to/file.txt

Compression Utilities

ToolExtensionCommandNotes
gzip.gzgzip file / gunzip file.gzFast, moderate ratio
bzip2.bz2bzip2 file / bunzip2 file.bz2Slower, better ratio
xz.xzxz file / unxz file.xzBest ratio, CPU intensive
zip.zipzip -r out.zip dir/ / unzip out.zipCross-platform friendly
Tip: Use tar -czvf backup-$(date +%F).tar.gz /data in a cron job for simple dated backups.

10 grep & Regular Expressions

Searching text with pattern matching

grep (Global Regular Expression Print) searches text for lines matching a pattern. Combined with regular expressions, it becomes one of the most powerful tools in the Linux toolbox.

Basic search.

bash
grep "error" logfile.txt

Case-insensitive.

bash
grep -i "error" logfile.txt

Recursive search in directory.

bash
grep -r "TODO" ./src

Show line numbers.

bash
grep -n "error" logfile.txt

Invert match (lines NOT containing pattern)

bash
grep -v "debug" logfile.txt

Count matches.

bash
grep -c "error" logfile.txt

Show only the matched text.

bash
grep -o "[0-9]\+" file.txt

Whole word match.

bash
grep -w "cat" file.txt

Extended regex (ERE) - avoids escaping +, ?, |, ()

bash
grep -E "error|warning|fatal" logfile.txt

Context lines.

bash
grep -A 3 "Exception" log.txt

3 lines After.

bash
grep -B 3 "Exception" log.txt

3 lines Before.

bash
grep -C 3 "Exception" log.txt

3 lines Context (both)

Regular Expression Basics

PatternMeaningExample
.Any single characterc.t → cat, cut, c9t
*Zero or more of previousab*c → ac, abc, abbc
^Start of line^Error
$End of linedone$
[abc]Character class[aeiou]
[^abc]Negated class[^0-9]
\d / [0-9]Digit[0-9]\+
+ (ERE)One or morea+
? (ERE)Zero or onecolou?r
| (ERE)Alternation (OR)cat|dog

11 sed Stream Editor

Non-interactive text transformation

sed (Stream EDitor) processes text line by line, applying commands like substitution, deletion, or insertion — ideal for scripted, repeatable edits across files.

Substitute first match per line.

bash
sed 's/foo/bar/' file.txt

Substitute ALL matches per line (global)

bash
sed 's/foo/bar/g' file.txt

Case-insensitive substitution.

bash
sed 's/foo/bar/gi' file.txt

Edit file in place (with backup)

bash
sed -i.bak 's/foo/bar/g' file.txt

Edit in place (no backup)

bash
sed -i 's/foo/bar/g' file.txt

Delete lines matching a pattern.

bash
sed '/^#/d' config.txt

Delete comment lines.

Print specific line range.

bash
sed -n '5,10p' file.txt

Delete a specific line number.

bash
sed '3d' file.txt

Insert a line before/after a match.

bash
sed '/pattern/i\New line before' file.txt
bash
sed '/pattern/a\New line after' file.txt

Multiple commands.

bash
sed -e 's/foo/bar/' -e 's/baz/qux/' file.txt
Tip: Use a different delimiter when your pattern contains slashes: sed 's#/usr/local#/opt#g'.

12 awk Programming

Pattern scanning and column-based text processing

awk is a full text-processing language built around the idea of splitting each input line into fields. It excels at reports, column extraction, and quick data summaries.

Print specific columns ($1 = first field, $NF = last field)

bash
awk '{print $1, $3}' data.txt

Custom field separator (e.g. CSV)

bash
awk -F',' '{print $2}' data.csv

Filter rows matching a condition.

bash
awk '$3 > 100 {print $1}' data.txt

Sum a column.

bash
awk '{sum += $2} END {print sum}' data.txt

Print line count (like wc -l)

bash
awk 'END {print NR}' file.txt

Combine pattern + action.

bash
awk '/error/ {count++} END {print count " errors"}' log.txt

Print disk usage per user process (ps + awk)

bash
ps aux | awk '{print $1, $4}' | sort -k2 -nr | head
Built-in variables: NR (current record/line number), NF (number of fields on current line), FS (field separator), OFS (output field separator).

13 Pipes & Redirection

Chaining commands and controlling input/output streams

Linux gives every process three standard streams: stdin (0), stdout (1), and stderr (2). Redirection and pipes let you rewire these streams to build powerful command chains.

Pipe: send stdout of one command to stdin of next.

bash
ls -l | grep ".txt" | wc -l

Redirect stdout to a file (overwrite)

bash
echo "hello" > out.txt

Redirect stdout to a file (append)

bash
echo "world" >> out.txt

Redirect stderr only.

bash
command 2> errors.log

Redirect both stdout and stderr.

bash
command > all.log 2>&1
bash
command &> all.log

Shorthand.

Discard output.

bash
command > /dev/null 2>&1

Redirect stdin from a file.

bash
wc -l < file.txt

Here-document (multi-line stdin)

bash
cat << EOF > file.txt
bash
line one
bash
line two
bash
EOF

Tee: write to file AND stdout simultaneously.

bash
ls -l | tee listing.txt

Command substitution.

bash
files=$(ls *.txt)
bash
echo "Found: $files"

14 Users & Groups

Multi-user account management

Linux is a multi-user system by design. Every process runs as a specific user, and access to files is governed by that user's identity and group memberships, stored in /etc/passwd, /etc/shadow, and /etc/group.

Create a user.

bash
useradd -m -s /bin/bash alice

-m creates home dir, -s sets shell.

bash
adduser alice

Interactive, friendlier (Debian/Ubuntu)

Set / change password.

bash
passwd alice

Modify a user.

bash
usermod -aG sudo alice

Add to sudo group (-a = append, don't overwrite)

bash
usermod -s /bin/zsh alice

Change shell.

bash
usermod -L alice

Lock account.

Delete a user.

bash
userdel alice

Keep home directory.

bash
userdel -r alice

Remove home directory too.

Group management.

bash
groupadd developers
bash
groupdel developers
bash
gpasswd -a alice developers

Add user to group.

bash
gpasswd -d alice developers

Remove user from group.

View identity and group info.

bash
id alice
bash
groups alice
bash
whoami
bash
who

Who is logged in.

bash
w

Who + what they're doing.

Key Files

FileContents
/etc/passwdUsername, UID, GID, home dir, shell (no passwords)
/etc/shadowEncrypted passwords, expiration policy (root-only readable)
/etc/groupGroup names, GIDs, and member lists
/etc/sudoersRules for who can use sudo and how

15 sudo & Privileges

Controlled privilege escalation

sudo ("superuser do") lets authorized users run commands as another user — typically root — without sharing the root password, while logging every invocation for accountability.

Run a single command as root.

bash
sudo apt update

Run as a specific user.

bash
sudo -u www-data whoami

Open a root shell.

bash
sudo -i
bash
sudo -s

Edit sudoers safely (validates syntax before saving)

bash
visudo

Check what you're allowed to run.

bash
sudo -l

Re-run the previous command with sudo.

bash
sudo !!

sudoers Syntax

/etc/sudoers - format: user host=(runas) commands.

bash
alice ALL=(ALL:ALL) ALL

Full sudo access.

bash
bob ALL=(ALL) NOPASSWD: ALL

No password prompt.

bash
%developers ALL=(ALL) /usr/bin/systemctl restart nginx

Group, one command only.

Warning: Always edit /etc/sudoers with visudo, never directly — a syntax error can lock you out of privilege escalation entirely.

16 SSH & Remote Access

Secure remote administration

SSH (Secure Shell) provides encrypted remote login and file transfer, replacing insecure protocols like telnet and rsh. It underpins virtually all remote Linux server administration.

Connect to a remote host.

bash
ssh user@192.168.1.10
bash
ssh -p 2222 user@host

Custom port.

bash
ssh -i ~/.ssh/id_ed25519 user@host

Specific key.

Generate a key pair.

bash
ssh-keygen -t ed25519 -C "me@example.com"

Copy public key to server for passwordless login.

bash
ssh-copy-id user@host

Copy files over SSH.

bash
scp file.txt user@host:/remote/path/
bash
scp -r localdir/ user@host:/remote/path/
bash
rsync -avz localdir/ user@host:/remote/path/

Faster, incremental.

Run a remote command without an interactive shell.

bash
ssh user@host "df -h"

Port forwarding (tunnel local port to remote service)

bash
ssh -L 8080:localhost:80 user@host

SSH Config File

Save per-host shortcuts to ~/.ssh/config instead of typing the full connection details each time.

bash
Host myserver HostName 192.168.1.10 User alice Port 2222 IdentityFile ~/.ssh/id_ed25519

With that alias defined, connecting is as simple as:

bash
ssh myserver

SSH reads the host, user, port, and key from the config file automatically.

Tip: Disable password authentication in /etc/ssh/sshd_config (PasswordAuthentication no) once key-based login works, to shut down brute-force attempts entirely.

17 Processes & Jobs

Monitoring and controlling running programs

Every running program is a process with a unique Process ID (PID). Linux provides rich tooling to inspect, prioritize, and manage processes, plus job control for foreground/background execution within a shell session.

View running processes.

bash
ps aux

All processes, all users.

bash
ps -ef

Full-format listing.

bash
ps aux | grep nginx

Find a specific process.

Interactive real-time monitor.

bash
top
bash
htop

Nicer UI (install separately)

Process tree.

bash
pstree

Job control.

bash
command &

Run in background.

bash
jobs

List background jobs.

bash
fg %1

Bring job 1 to foreground.

bash
bg %1

Resume job 1 in background.

bash
Ctrl+Z

Suspend current foreground job.

Keep a process running after logout.

bash
nohup long-task.sh &
bash
disown

Change process priority (nice value: -20 highest, 19 lowest)

bash
nice -n 10 long-task.sh
bash
renice 5 -p 1234

18 Signals & Kill

Communicating with and terminating processes

Signals are the kernel's way of notifying a process of an event — from a graceful termination request to an immediate, unstoppable kill.

SignalNumberMeaning
SIGHUP1Hangup — often used to reload config
SIGINT2Interrupt (Ctrl+C)
SIGKILL9Force kill — cannot be caught or ignored
SIGTERM15Graceful termination request (default)
SIGSTOP19Pause process — cannot be caught
SIGCONT18Resume a stopped process

Send SIGTERM (graceful) by PID.

bash
kill 1234

Force kill.

bash
kill -9 1234
bash
kill -SIGKILL 1234

Kill by process name.

bash
pkill firefox
bash
killall nginx

Send signal to all jobs in current shell.

bash
kill 0

List available signals.

bash
kill -l
Warning: Prefer SIGTERM (default) over SIGKILL whenever possible — it gives the process a chance to close files and clean up. Reserve -9 for unresponsive processes.

19 Cron & Scheduling

Automating recurring tasks

cron is a time-based job scheduler that runs commands automatically at specified intervals, defined per-user in a crontab file.

Edit your crontab.

bash
crontab -e

List your crontab.

bash
crontab -l

Remove your crontab.

bash
crontab -r

Format: minute hour day month weekday command.

bash
0 3 * * * /usr/local/bin/backup.sh

Daily at 3:00 AM.

bash
*/15 * * * * /usr/local/bin/healthcheck.sh

Every 15 minutes.

bash
0 0 * * 0 /usr/local/bin/weekly.sh

Every Sunday at midnight.

bash
30 9 1 * * /usr/local/bin/report.sh

1st of every month, 9:30 AM.

systemd Timers (Modern Alternative)

A timer unit (/etc/systemd/system/backup.timer) pairs with a matching .service unit of the same name to schedule it.

bash
[Unit] Description=Run backup daily [Timer] OnCalendar=daily Persistent=true [Install] WantedBy=timers.target

Enable the timer and confirm it's scheduled.

bash
systemctl enable --now backup.timer

Enables the timer at boot and starts it immediately.

bash
systemctl list-timers

Lists active timers and when each will next run.

Tip: systemd timers log to journalctl automatically and support dependency ordering — worth adopting for anything beyond simple schedules.

20 Network Commands

Diagnosing and configuring connectivity

Interface configuration (modern)

bash
ip a

Show all addresses.

bash
ip link show

Show interfaces.

bash
ip route

Show routing table.

bash
ip addr add 192.168.1.5/24 dev eth0

Connectivity testing.

bash
ping -c 4 google.com

4 packets.

bash
traceroute google.com

Path to destination.

bash
mtr google.com

Continuous traceroute + ping.

Open connections and listening ports.

bash
ss -tulpn

Modern replacement for netstat.

bash
netstat -tulpn

Download files.

bash
curl -O https://example.com/file.tar.gz
bash
wget https://example.com/file.tar.gz

Test an HTTP endpoint.

bash
curl -I https://example.com

Headers only.

bash
curl -v https://example.com

Verbose (show handshake)

Show/renew DHCP lease.

bash
dhclient -r eth0
bash
dhclient eth0

21 Firewall & iptables

Filtering network traffic

Linux firewalling is built on the kernel's netfilter framework. iptables is the classic low-level tool; ufw and firewalld are friendlier front-ends built on top of it (or nftables).

ufw (Uncomplicated Firewall — Debian/Ubuntu)

bash
ufw enable
bash
ufw status verbose
bash
ufw allow 22/tcp

Allow SSH.

bash
ufw allow from 192.168.1.0/24
bash
ufw deny 23
bash
ufw delete allow 22/tcp

firewalld (RHEL/Fedora)

bash
firewall-cmd --state
bash
firewall-cmd --zone=public --add-service=http --permanent
bash
firewall-cmd --zone=public --add-port=8080/tcp --permanent
bash
firewall-cmd --reload
bash
firewall-cmd --list-all

iptables (Low-Level)

List current rules.

bash
iptables -L -n -v

Allow incoming SSH.

bash
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

Drop all other incoming traffic.

bash
iptables -A INPUT -j DROP

Save rules (Debian/Ubuntu, via iptables-persistent)

bash
iptables-save > /etc/iptables/rules.v4
Warning: Always allow SSH before enabling a deny-all policy on a remote server — locking yourself out often requires physical/console access to fix.

22 DNS & Hostname

Name resolution and host identity

Query DNS records.

bash
dig example.com
bash
dig example.com MX

Mail records.

bash
dig +short example.com

Just the IP.

bash
nslookup example.com

Reverse lookup.

bash
dig -x 8.8.8.8

Hostname management.

bash
hostname

Show current hostname.

bash
hostnamectl set-hostname web01
bash
hostnamectl status

Local name resolution (checked before DNS)

bash
cat /etc/hosts

127.0.0.1 localhost.

192.168.1.5 web01.local web01.

DNS resolver configuration.

bash
cat /etc/resolv.conf
Tip: Resolution order is controlled by /etc/nsswitch.conf — the hosts: line typically reads files dns, meaning /etc/hosts is checked first.

23 APT (Debian/Ubuntu)

Package management on Debian-based distributions

Update package index.

bash
apt update

Upgrade installed packages.

bash
apt upgrade
bash
apt full-upgrade

Also handles dependency changes/removals.

Install / remove packages.

bash
apt install nginx
bash
apt remove nginx

Keep config files.

bash
apt purge nginx

Remove config files too.

bash
apt autoremove

Remove unused dependencies.

Search and info.

bash
apt search nginx
bash
apt show nginx
bash
dpkg -l | grep nginx

List installed packages.

bash
dpkg -L nginx

List files owned by package.

Install a local .deb file.

bash
dpkg -i package.deb
bash
apt install -f

Fix missing dependencies afterward.

Hold a package at its current version.

bash
apt-mark hold nginx

24 DNF/YUM (RHEL/Fedora)

Package management on Red Hat-based distributions

dnf is the modern successor to yum, used on Fedora, RHEL 8+, CentOS Stream, AlmaLinux, and Rocky Linux.

Update package index and packages.

bash
dnf check-update
bash
dnf upgrade

Install / remove.

bash
dnf install httpd
bash
dnf remove httpd
bash
dnf autoremove

Search and info.

bash
dnf search httpd
bash
dnf info httpd
bash
rpm -qa | grep httpd

List installed packages.

bash
rpm -ql httpd

List files owned by package.

Install a local .rpm file.

bash
dnf install ./package.rpm

Manage repositories.

bash
dnf repolist
bash
dnf config-manager --add-repo https://example.com/repo

Groups of related packages.

bash
dnf group list
bash
dnf group install "Development Tools"

25 Pacman (Arch)

Package management on Arch Linux and derivatives

Sync repo index and upgrade whole system (do together, always)

bash
pacman -Syu

Install a package.

bash
pacman -S neovim

Remove a package.

bash
pacman -R neovim

Keep dependencies.

bash
pacman -Rs neovim

Remove unused dependencies too.

Search.

bash
pacman -Ss neovim

Info.

bash
pacman -Si neovim

Remote package info.

bash
pacman -Qi neovim

Installed package info.

List installed packages.

bash
pacman -Q
bash
pacman -Qe

Explicitly installed (not deps)

Clean package cache.

bash
pacman -Sc

AUR helper (not part of pacman itself)

bash
yay -S google-chrome
Tip: Never run pacman -Sy (sync only) without -u right after — a partial upgrade can break dependency resolution on a rolling-release system.

26 Snap, Flatpak & AppImage

Distribution-agnostic packaging formats

These formats bundle an application with its dependencies so it runs consistently across distributions, at the cost of larger download sizes and slightly slower startup.

Snap (Canonical)

bash
snap install code --classic
bash
snap list
bash
snap remove code
bash
snap refresh

Flatpak (community/Red Hat backed)

bash
flatpak install flathub org.gimp.GIMP
bash
flatpak list
bash
flatpak run org.gimp.GIMP
bash
flatpak uninstall org.gimp.GIMP
bash
flatpak update

AppImage - single portable executable, no install needed.

bash
chmod +x App.AppImage
bash
./App.AppImage
FormatSandboxingBacked ByTypical Use
SnapYes (strict confinement)CanonicalUbuntu desktop & server apps
FlatpakYes (portals)Community, GNOME/KDEDesktop GUI apps
AppImageNoCommunityPortable, no-install apps

27 systemd & Services

The modern init system and service manager

systemd is PID 1 on nearly all modern distributions — it boots the system, manages services (units), handles logging, and coordinates dependencies between them.

Service control.

bash
systemctl start nginx
bash
systemctl stop nginx
bash
systemctl restart nginx
bash
systemctl reload nginx

Reload config without downtime.

bash
systemctl status nginx

Enable/disable at boot.

bash
systemctl enable nginx
bash
systemctl disable nginx
bash
systemctl enable --now nginx

Enable and start immediately.

List units.

bash
systemctl list-units --type=service
bash
systemctl list-unit-files --state=enabled

Check if active/enabled.

bash
systemctl is-active nginx
bash
systemctl is-enabled nginx

Writing a Custom Unit File

A minimal service unit for a long-running app, saved as /etc/systemd/system/myapp.service.

bash
[Unit] Description=My Application After=network.target [Service] Type=simple User=appuser WorkingDirectory=/opt/myapp ExecStart=/usr/bin/python3 /opt/myapp/main.py Restart=on-failure [Install] WantedBy=multi-user.target

After creating or editing a unit file, reload systemd's configuration and start the service.

bash
systemctl daemon-reload

Tells systemd to re-read unit files, picking up new or changed ones.

bash
systemctl enable --now myapp

Enables the service at boot and starts it right away.

28 journalctl & Logs

Reading the systemd journal

journalctl queries the binary, structured logs collected by journald — covering the kernel, services, and boot process in one unified place.

View all logs (oldest first)

bash
journalctl

Follow logs live (like tail -f)

bash
journalctl -f

Logs for a specific service.

bash
journalctl -u nginx.service

Logs since a given time.

bash
journalctl --since "1 hour ago"
bash
journalctl --since "2026-07-20" --until "2026-07-21"

Logs from the current boot only.

bash
journalctl -b

Filter by priority (0=emerg ... 7=debug)

bash
journalctl -p err

Kernel messages only.

bash
journalctl -k

Limit disk usage of the journal.

bash
journalctl --vacuum-size=200M
bash
journalctl --vacuum-time=2weeks
Traditional logs: Text-based logs still live in /var/log (e.g. /var/log/syslog, /var/log/auth.log), readable directly with tail, less, or grep.

29 Kernel Modules

Extending kernel functionality at runtime

Loadable Kernel Modules (LKMs) add drivers and functionality to a running kernel without a reboot — most hardware drivers and filesystems are implemented this way.

List loaded modules.

bash
lsmod

Show details about a module.

bash
modinfo nvidia

Load / unload a module.

bash
modprobe nvidia
bash
modprobe -r nvidia

Remove (and unused dependencies)

bash
insmod ./mymodule.ko

Load directly from file (no dependency resolution)

bash
rmmod mymodule

Persist a module across reboots.

bash
echo "nvidia" >> /etc/modules-load.d/nvidia.conf

Blacklist a module (prevent auto-load)

bash
echo "blacklist nouveau" >> /etc/modprobe.d/blacklist.conf

Kernel version and info.

bash
uname -r
bash
uname -a
bash
dmesg | tail

Recent kernel ring buffer messages.

30 Disk & Storage

Partitioning, filesystems, and monitoring space

Disk usage overview.

bash
df -h

Free/used space per mounted filesystem.

Directory size breakdown.

bash
du -sh /var/log

Total size of a directory.

bash
du -h --max-depth=1 /home

Per-subdirectory sizes.

List block devices and partitions.

bash
lsblk
bash
fdisk -l

Partition a disk (interactive)

bash
fdisk /dev/sdb
bash
parted /dev/sdb

Create a filesystem.

bash
mkfs.ext4 /dev/sdb1
bash
mkfs.xfs /dev/sdb1

Mount / unmount.

bash
mount /dev/sdb1 /mnt/data
bash
umount /mnt/data

Persistent mounts (edit carefully!)

bash
cat /etc/fstab

UUID=xxxx /mnt/data ext4 defaults 0 2.

Check and repair a filesystem (must be unmounted)

bash
fsck /dev/sdb1

Logical Volume Manager (LVM) basics.

bash
pvcreate /dev/sdb1
bash
vgcreate vg_data /dev/sdb1
bash
lvcreate -L 50G -n lv_data vg_data
Tip: Always find the UUID with blkid and use it in /etc/fstab instead of a device name like /dev/sdb1, since device names can shift between boots.

31 Bash Basics

Writing your first shell scripts

A shell script is a text file of commands executed in sequence by an interpreter, declared via a shebang line. Scripts automate repetitive administration tasks. Here's a simple deployment script, saved as deploy.sh:

bash
#!/bin/bash echo "Starting deployment..." cd /var/www/app git pull origin main npm install systemctl restart myapp echo "Deployment complete!"

Make it executable and run it.

bash
chmod +x deploy.sh
bash
./deploy.sh

Or run without executable bit.

bash
bash deploy.sh

Strict mode - fail fast on errors (recommended at top of scripts)

bash
set -euo pipefail

-e: exit on any error -u: error on unset variables -o pipefail: catch errors in pipes.

32 Variables & Expansion

Storing and manipulating data in shell scripts

Declare and use variables (no spaces around =)

bash
name="Alice"
bash
echo "Hello, $name"
bash
echo "Hello, ${name}!"

Braces avoid ambiguity.

Command output into a variable.

bash
count=$(ls | wc -l)

Arithmetic.

bash
result=$(( 5 + 3 ))
bash
echo $(( count * 2 ))

Arrays.

bash
fruits=("apple" "banana" "cherry")
bash
echo ${fruits[0]}
bash
echo ${fruits[@]}

All elements.

bash
echo ${#fruits[@]}

Array length.

Default values / parameter expansion.

bash
echo ${name:-"Unknown"}

Use default if unset.

bash
echo ${#name}

String length.

bash
echo ${name/Alice/Bob}

Substitution.

Special variables.

bash
echo $0

Script name.

bash
echo $1 $2

First and second arguments.

bash
echo $#

Number of arguments.

bash
echo $@

All arguments.

bash
echo $?

Exit code of last command.

bash
echo $$

PID of current script.

33 Conditionals & Loops

Control flow in shell scripts

An if/elif/else block branches on the exit status of a test. Each condition is tried in order until one succeeds.

bash
if [ $count -gt 10 ]; then echo "Large" elif [ $count -gt 0 ]; then echo "Small" else echo "Empty" fi

A one-line form works for a single string comparison.

bash
if [ "$name" == "Alice" ]; then echo "Hi Alice"; fi

Runs the command only if $name equals "Alice".

File test operators check whether a path exists and what kind of file it is, without needing to open it.

bash
if [ -f /etc/passwd ]; then echo "exists"; fi

-f is true if the path exists and is a regular file.

bash
if [ -d /var/log ]; then echo "is a directory"; fi

-d is true if the path exists and is a directory.

A for loop iterates over a fixed list of words or values.

bash
for i in 1 2 3 4 5; do echo "Number: $i" done

A glob pattern in the list lets the loop walk over matching files.

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

C-style for loops give explicit control over the counter, using an initializer, a condition, and an increment.

bash
for ((i=0; i<10; i++)); do echo $i done

A while loop keeps running as long as its test succeeds.

bash
count=0 while [ $count -lt 5 ]; do echo "Count: $count" count=$((count + 1)) done

A case statement matches a value against several patterns, similar to a switch statement in other languages.

bash
case $1 in start) echo "Starting..." ;; stop) echo "Stopping..." ;; *) echo "Usage: $0 {start|stop}" ;; esac

34 Functions

Reusable blocks of shell logic

Define a function by name, then call it like any other command. local scopes a variable to the function so it doesn't leak into the rest of the script.

bash
greet() { local name=$1 echo "Hello, $name!" } greet "Alice"

A function can return a value through its exit code — but only as an integer from 0 to 255, since that's all an exit code can hold. By convention 0 means success/true and anything else means failure/false.

bash
is_even() { if [ $(( $1 % 2 )) -eq 0 ]; then return 0 else return 1 fi } if is_even 4; then echo "even"; fi

To return an actual value (not just success/failure), the common pattern is to echo it and capture the output with command substitution.

bash
get_sum() { echo $(( $1 + $2 )) } total=$(get_sum 3 4)

The ${1:-default} expansion gives a parameter a default value when the caller doesn't provide one.

bash
backup() { local dir=${1:-/home} tar -czf backup.tar.gz "$dir" }

35 Security Basics

Hardening a Linux system

Linux security is layered: user privilege separation, filesystem permissions, network filtering, and mandatory access control all work together. A few practices cover most of the risk for a typical server.

  • Keep the system updated: apt upgrade / dnf upgrade regularly, or enable unattended security updates.
  • Disable root SSH login: set PermitRootLogin no in /etc/ssh/sshd_config.
  • Use key-based SSH auth and disable password authentication once configured.
  • Principle of least privilege: grant only the permissions and sudo rights a user or service actually needs.
  • Enable a firewall and only open the ports you actually use.
  • Use fail2ban to auto-ban IPs after repeated failed login attempts.

Install and enable fail2ban.

bash
apt install fail2ban
bash
systemctl enable --now fail2ban
bash
fail2ban-client status sshd

Audit listening ports (attack surface)

bash
ss -tulpn

Check for failed login attempts.

bash
journalctl -u ssh | grep "Failed password"
bash
lastb

Failed login history.

Check for world-writable files (common misconfiguration)

bash
find / -xdev -type f -perm -0002 2>/dev/null

36 SELinux & AppArmor

Mandatory Access Control (MAC) systems

Standard permissions are discretionary — the owner decides access. SELinux (Red Hat family) and AppArmor (Debian/Ubuntu/SUSE family) add mandatory access control: even root can be confined by policy.

SELinux

Check current mode.

bash
getenforce

Enforcing / Permissive / Disabled.

Temporarily change mode (until reboot)

bash
setenforce 0

Permissive (log only, don't block)

bash
setenforce 1

Enforcing.

View file/process context labels.

bash
ls -Z /var/www/html
bash
ps -eZ

Restore default context after moving a file.

bash
restorecon -Rv /var/www/html

View recent denials.

bash
ausearch -m avc -ts recent
bash
sealert -a /var/log/audit/audit.log

AppArmor

Status of all profiles.

bash
aa-status

Put a profile into complain (log-only) or enforce mode.

bash
aa-complain /etc/apparmor.d/usr.sbin.nginx
bash
aa-enforce /etc/apparmor.d/usr.sbin.nginx
Note: Never disable SELinux/AppArmor outright to "fix" a permission problem — switch to permissive/complain mode temporarily, read the denial logs, and adjust the policy instead.

37 Encryption & Keys

Protecting data at rest and in transit

Full-disk / partition encryption with LUKS.

bash
cryptsetup luksFormat /dev/sdb1
bash
cryptsetup open /dev/sdb1 secure_data
bash
mkfs.ext4 /dev/mapper/secure_data
bash
cryptsetup close secure_data

File/text encryption with GPG.

bash
gpg --gen-key
bash
gpg -c secret.txt

Symmetric (password-based)

bash
gpg secret.txt.gpg

Decrypt.

bash
gpg --encrypt --recipient bob@example.com file.txt
bash
gpg --decrypt file.txt.gpg > file.txt

Generate a checksum to verify integrity.

bash
sha256sum file.iso
bash
sha256sum -c checksums.txt

TLS certificates (Let's Encrypt via certbot)

bash
certbot --nginx -d example.com
bash
certbot renew --dry-run
Tip: Always back up a LUKS header (cryptsetup luksHeaderBackup) — losing it makes the encrypted data unrecoverable even with the correct passphrase.

38 Containers & Docker

Lightweight, isolated application environments

Containers package an application with its dependencies using kernel features like namespaces (isolation) and cgroups (resource limits) — no separate guest kernel required, unlike a VM.

Run a container.

bash
docker run -d -p 8080:80 --name web nginx

List running / all containers.

bash
docker ps
bash
docker ps -a

Stop, start, remove.

bash
docker stop web
bash
docker start web
bash
docker rm web

Logs and shell access.

bash
docker logs -f web
bash
docker exec -it web bash

Images.

bash
docker images
bash
docker build -t myapp:latest .
bash
docker pull ubuntu:24.04
bash
docker rmi myapp:latest

Clean up unused resources.

bash
docker system prune -a

Dockerfile Basics

A Dockerfile describes how to build an image, step by step, layer by layer.

dockerfile
FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "app.py"]

Docker Compose

Compose defines multiple related containers — here a web app and its database — as one file.

yaml
services: web: build: . ports: - "8000:8000" db: image: postgres:16 environment: POSTGRES_PASSWORD: secret
bash
docker compose up -d

Builds and starts every service defined in the file, in the background.

39 Virtualization

Running full virtual machines on Linux

Unlike containers, virtual machines run their own complete kernel via a hypervisor. Linux's built-in hypervisor is KVM (Kernel-based Virtual Machine), usually driven through QEMU and managed with libvirt.

Check for hardware virtualization support.

bash
egrep -c '(vmx|svm)' /proc/cpuinfo

Install KVM/QEMU + libvirt tooling (Debian/Ubuntu)

bash
apt install qemu-kvm libvirt-daemon-system virtinst virt-manager

Manage VMs with virsh.

bash
virsh list --all
bash
virsh start myvm
bash
virsh shutdown myvm
bash
virsh destroy myvm

Force power off.

Create a VM from the command line.

bash
virt-install --name myvm --memory 2048 --vcpus 2 \ --disk size=20 --cdrom /path/to/os.iso --os-variant ubuntu24.04
AspectContainersVirtual Machines
KernelShared with hostOwn dedicated kernel
Startup timeMilliseconds to secondsSeconds to minutes
Isolation strengthProcess-levelHardware-level
OverheadLowHigher (full OS per VM)

40 Performance Tuning

Diagnosing and improving system performance

CPU load and averages.

bash
uptime

Load averages: 1, 5, 15 min.

bash
vmstat 1

Live CPU/memory/IO stats.

bash
mpstat -P ALL 1

Per-core CPU usage.

Memory usage.

bash
free -h

Disk I/O.

bash
iostat -x 1
bash
iotop

Per-process disk I/O (like top)

Find what's consuming the most CPU/memory.

bash
ps aux --sort=-%cpu | head
bash
ps aux --sort=-%mem | head

Trace open files and syscalls of a process.

bash
lsof -p 1234
bash
strace -p 1234

Network throughput.

bash
iftop
bash
nload
Tip: A load average above your core count sustained over time usually means CPU is the bottleneck; high iowait in vmstat points to disk I/O instead — diagnose before you tune.