Complete Linux OS Tutorial with Usage Examples
1. Introduction to Linux
Linux is a family of open-source Unix-like operating systems based on the Linux kernel. It is one of the most popular operating systems in the world, powering a vast array of devices from smartphones (Android) and embedded systems to supercomputers and servers. While the kernel is Linux, the complete operating system is often referred to as a "Linux distribution" or "distro".
Why Learn Linux?
- Ubiquitous in Servers: Dominates the server and cloud computing market (AWS, Azure, GCP all rely heavily on Linux).
- Open Source & Free: Freely available, highly customizable, and supported by a vast community.
- Security: Generally considered more secure than other operating systems, especially for servers.
- Flexibility: Adaptable to various hardware and use cases, from desktops to IoT devices.
- Developer Friendly: Provides a powerful command-line interface and tools essential for developers and system administrators.
- Career Opportunities: Strong demand for Linux skills in IT, DevOps, Cloud Computing, and Cybersecurity.
2. Core Components of Linux
A Linux operating system is a collection of several distinct components working together:
- Kernel: The heart of the OS. It manages system resources (CPU, memory, devices), acts as a bridge between hardware and software, and schedules processes.
- Bootloader (e.g., GRUB): The initial software that runs when a computer starts. Its job is to load the kernel into memory.
- Init System (e.g., systemd, SysVinit): The first process started by the kernel. It's responsible for bootstrapping user-space, initializing, and managing all other processes and services during boot and shutdown.
- Daemons: Background processes that run independently of user interaction. They perform various tasks like handling network services (`sshd` for SSH), monitoring hardware, or managing system events.
- Shell (e.g., Bash, Zsh): A command-line interface (CLI) that allows users to interact with the system by typing commands. It interprets commands and executes them.
- Graphical Server (e.g., X Window System, Wayland): Responsible for managing graphical elements and rendering them on the screen, providing the foundation for GUIs.
- Desktop Environment (e.g., GNOME, KDE Plasma, XFCE): Provides a complete graphical user interface including a desktop, taskbar, icons, and various applications, built on top of the graphical server.
- Window Manager: A component (often part of a Desktop Environment) that specifically manages the placement, appearance, and behavior of individual windows.
3. Linux Distributions & Desktop Environments
A Linux distribution is a complete operating system built on the Linux kernel, along with a collection of software packages, utilities, and a desktop environment. There are hundreds of distributions, each catering to different needs.
Popular Linux Distributions:
- Ubuntu: Very popular, user-friendly, great for desktops and servers. (Debian-based)
- Debian: Stable, foundational distribution, Ubuntu is based on it.
- Fedora: Community-driven, bleeding-edge features, often a testing ground for Red Hat Enterprise Linux. (Red Hat-based)
- CentOS/RHEL (Red Hat Enterprise Linux): Enterprise-grade, stable, commercially supported.
- Linux Mint: User-friendly, based on Ubuntu, often recommended for Windows users transitioning to Linux.
- Arch Linux: Rolling release, highly customizable, requires more manual configuration.
- Kali Linux: Specialized for penetration testing and digital forensics (comes with many security tools pre-installed).
Common Desktop Environments (GUIs):
- GNOME: Modern, sleek, user-friendly interface. Default for Ubuntu, Fedora.
- KDE Plasma: Highly customizable, feature-rich, powerful. Default for Kubuntu, Fedora KDE.
- XFCE: Lightweight, fast, resource-efficient. Good for older hardware. Default for Xubuntu.
- LXQt: Extremely lightweight, ideal for very old hardware or minimal systems.
- Cinnamon: Familiar layout, aims for a traditional desktop experience. Default for Linux Mint.
4. Installation Methods
You can experience Linux in various ways:
Recommendation: Start with installing Ubuntu Desktop in a Virtual Machine (e.g., VirtualBox). This provides a full GUI experience in a safe, isolated environment.
5. Basic Linux Commands (CLI)
The command-line interface (CLI) is a powerful way to interact with Linux. Open a "Terminal" application in your Linux GUI (e.g., Ctrl + Alt + t on Ubuntu).
- `pwd` (Print Working Directory): Shows your current directory.
pwd
# Output: /home/yourusername
- `ls` (List): Lists files and directories in the current location.
ls # List contents of current directory
ls -l # Long format (details like permissions, owner, size, date)
ls -a # List all files, including hidden ones (starting with .)
ls -la # Combine long format and show hidden files
ls /etc # List contents of a specific directory (/etc)
- `cd` (Change Directory): Navigates between directories.
cd Documents # Move into the 'Documents' directory
cd .. # Move up one directory (to the parent directory)
cd ~ # Move to your home directory
cd / # Move to the root directory
cd - # Move to the previous directory you were in
- `mkdir` (Make Directory): Creates new directories.
mkdir my_new_folder
mkdir -p projects/my_project # Create parent directories if they don't exist
- `rmdir` (Remove Directory): Deletes empty directories.
rmdir my_empty_folder
- `touch`: Creates empty files or updates a file's timestamp.
touch newfile.txt
touch another_file.sh
- `cp` (Copy): Copies files or directories.
cp file1.txt file2.txt # Copy file1.txt to file2.txt in same directory
cp file.txt /tmp/ # Copy file.txt to /tmp/ directory
cp -r my_folder /backup/ # Copy a directory recursively
- `mv` (Move): Moves or renames files/directories.
mv old_name.txt new_name.txt # Rename a file
mv file.txt /archive/ # Move file.txt to /archive/
- `rm` (Remove): Deletes files or directories.
rm unwanted_file.txt
rm -r old_folder # Remove a directory and its contents recursively (USE WITH CAUTION!)
rm -f stubborn_file.txt # Force remove (no prompt)
rm -rf very_important_folder # Force remove recursively (EXTREME CAUTION: Irreversible!)
- `cat` (Concatenate): Displays the content of files.
cat my_document.txt
cat /etc/os-release # Show OS information
- `less` / `more`: View file content page by page (better for large files than `cat`).
less /var/log/syslog # Press Space to scroll down, 'q' to quit
- `head` / `tail`: Display the beginning/end of a file.
head -n 5 file.txt # Show first 5 lines
tail -n 10 file.txt # Show last 10 lines
tail -f /var/log/auth.log # Follow a log file in real-time (Ctrl+C to exit)
- `echo`: Displays text or outputs text to files.
echo "Hello, Linux!"
echo "This is new text." > newfile.txt # Overwrite file
echo "Append this line." >> newfile.txt # Append to file
- `man` (Manual): Displays the manual page (documentation) for a command.
man ls # Press 'q' to quit the man page
- `sudo` (SuperUser Do): Executes a command with superuser (root) privileges. Required for many system administration tasks.
sudo apt update # Update package lists (requires password)
6. Linux File System Hierarchy (FHS)
Linux organizes all files and directories under a single root directory (`/`). This standardized structure is known as the Filesystem Hierarchy Standard (FHS).
- `/` (Root): The top-level directory. All other directories and files are located under it.
- `/bin`: (Binaries) Essential command binaries (e.g., `ls`, `cp`, `mv`). Available to all users, even in single-user mode.
- `/sbin`: (System Binaries) Essential system binaries for system administration (e.g., `fdisk`, `reboot`, `init`). Often requires root privileges.
- `/etc`: (Etcetera) Host-specific system-wide configuration files (e.g., network settings, user configurations).
- `/home`: Home directories for regular users (e.g., `/home/yourusername`). Contains user-specific files, documents, downloads.
- `/root`: The home directory for the `root` (superuser) account.
- `/opt`: (Optional) Optional application software packages. Often used for third-party software that is not part of the standard distribution.
- `/usr`: (Unix System Resources) Read-only user utilities and applications. Contains most user commands and applications, libraries, and documentation.
- `/usr/bin`: Most user commands.
- `/usr/local`: Locally installed software.
- `/var`: (Variable) Variable data files, such as log files (`/var/log`), mail queues, temporary files, and runtime data. Content changes frequently.
- `/tmp`: (Temporary) Temporary files created by users and applications. Contents are usually deleted on system reboot.
- `/dev`: (Devices) Contains special device files that represent hardware devices (e.g., `/dev/sda` for a hard drive).
- `/proc`: (Processes) A virtual filesystem providing information about running processes and kernel state.
- `/sys`: (System) A virtual filesystem providing access to kernel information and device drivers.
- `/boot`: Contains files needed to boot the operating system (e.g., GRUB bootloader files, Linux kernel).
- `/media`: Mount points for removable media (CD-ROMs, USB drives).
- `/mnt`: (Mount) Temporarily mounted filesystems.
7. File Permissions and Ownership
Linux is a multi-user operating system, and file permissions are crucial for security, controlling who can read, write, or execute files and directories.
Permissions (Read, Write, Execute):
- `r` (Read):
- For files: Can view content.
- For directories: Can list contents.
- `w` (Write):
- For files: Can modify or delete content.
- For directories: Can create, delete, or rename files within the directory.
- `x` (Execute):
- For files: Can run the file (if it's an executable program or script).
- For directories: Can enter (traverse) the directory.
Permission Categories:
Permissions are assigned to three categories:
- `u` (User/Owner): The user who owns the file or directory (usually the creator).
- `g` (Group): The group that owns the file or directory.
- `o` (Others): All other users on the system.
- `a` (All): Represents user, group, and others.
Viewing Permissions (`ls -l`):
ls -l my_script.sh
# Example Output: -rwxr-xr-- 1 user group 1234 Jul 19 10:00 my_script.sh
Breakdown of `-rwxr-xr--`:
- First character (`-`): File type (`-` for regular file, `d` for directory, `l` for symbolic link).
- Next 3 (`rwx`): Owner's permissions (read, write, execute).
- Next 3 (`r-x`): Group's permissions (read, execute, no write).
- Last 3 (`r--`): Others' permissions (read, no write, no execute).
Changing Permissions (`chmod`):
Can use symbolic mode (r, w, x, u, g, o, a) or octal (numeric) mode.
- Symbolic Mode:
chmod u+x my_script.sh # Add execute permission for owner
chmod go-w my_document.txt # Remove write permission for group and others
chmod a+rwx my_public_folder # Give all permissions to all (use with CAUTION)
- Octal (Numeric) Mode: Each permission has a numeric value: `r=4`, `w=2`, `x=1`. Sum the values for each category.
- `7` (rwx) = 4+2+1
- `6` (rw-) = 4+2+0
- `5` (r-x) = 4+0+1
- `4` (r--) = 4+0+0
chmod 755 my_script.sh # Owner: rwx, Group: r-x, Others: r-x
# Visual: -rwxr-xr-x
chmod 644 my_document.txt # Owner: rw-, Group: r--, Others: r--
# Visual: -rw-r--r--
chmod 700 my_private_key.pem # Only owner has read/write/execute access
Changing Ownership (`chown`, `chgrp`):
8. User and Group Management
Linux is multi-user, so managing user accounts and groups is fundamental for system administration and security.
User Accounts:
- `root`: The superuser. Has full administrative privileges (UID 0).
- System users: Accounts created by services/applications (UIDs usually 1-999).
- Normal users: Regular user accounts (UIDs usually 1000+).
Common Commands:
- `whoami`: Display the current username.
- `id`: Display user and group IDs for the current or specified user.
id yourusername
# Output example: uid=1000(yourusername) gid=1000(yourusername) groups=1000(yourusername),4(adm),24(cdrom)...
- `adduser`: Create a new user account. This command is a higher-level script that usually performs additional steps like creating a home directory and default group.
sudo adduser newuser
# You'll be prompted for a password and user details.
- `useradd`: A lower-level command for creating users. Doesn't create home directory or set password by default.
sudo useradd -m -s /bin/bash newuser2 # -m: create home dir, -s: set shell
- `passwd`: Set or change a user's password.
passwd # Change your own password
sudo passwd newuser # Set password for newuser
- `usermod`: Modify user account properties.
sudo usermod -aG sudo newuser # Add newuser to 'sudo' group (grant sudo privileges)
sudo usermod -l new_name old_name # Change username (careful with this!)
sudo usermod -d /home/customhome newuser # Change home directory
- `deluser` / `userdel`: Delete a user account.
sudo deluser olduser # Delete user, but leave home directory
sudo deluser --remove-home olduser2 # Delete user and home directory
Groups:
Groups are collections of users. Permissions can be assigned to groups, making it easier to manage access for multiple users.
- `addgroup`: Create a new group.
sudo addgroup mydevgroup
- `delgroup`: Delete a group.
sudo delgroup myoldgroup
- `gpasswd`: Manage group members.
sudo gpasswd -a newuser mydevgroup # Add newuser to mydevgroup
sudo gpasswd -d olduser mydevgroup # Remove olduser from mydevgroup
- `groups`: List groups a user belongs to.
groups # List groups for current user
groups newuser # List groups for newuser
Configuration Files:
- `/etc/passwd`: Stores basic user account information (username, UID, GID, home directory, shell). (No passwords here).
- `/etc/shadow`: Stores encrypted user passwords and password aging information (root-readable only).
- `/etc/group`: Stores information about groups (group name, GID, list of members).
- `/etc/sudoers`: Defines which users/groups can run `sudo` commands and what permissions they have (edited with `visudo`).
9. Package Management (apt, yum/dnf)
Linux distributions use package managers to automate the process of installing, updating, configuring, and removing software packages and their dependencies.
Debian-based Systems (Ubuntu, Debian, Kali) - `apt`:
Red Hat-based Systems (Fedora, CentOS, RHEL) - `yum` (older) / `dnf` (newer):
`dnf` is the modern successor to `yum` and is generally preferred.
- Update package lists (sync repositories):
sudo dnf check-update # yum check-update
- Install packages:
sudo dnf install httpd # Install Apache web server (httpd)
sudo dnf install git nano # Install multiple packages
- Upgrade installed packages:
sudo dnf upgrade # yum update
- Remove packages:
sudo dnf remove httpd # yum remove httpd
- Search for packages:
dnf search python3
- Show package details:
dnf info httpd
10. Process Management
Processes are instances of running programs. Managing them is a key aspect of system administration.
- `ps` (Process Status): Displays information about running processes.
ps aux # Show all running processes with user, CPU, memory usage
ps -ef # Show all processes in full format (more details)
ps -p <PID> # Show info for a specific Process ID
- `top`: Provides a real-time, dynamic view of running processes, CPU usage, memory usage, and other system information. Press q to quit.
top
- `htop`: An interactive process viewer, similar to `top` but with a more user-friendly interface. (Often needs to be installed: `sudo apt install htop`).
htop
- `kill`: Sends a signal to a process, typically to terminate it. Requires the Process ID (PID).
kill <PID> # Sends SIGTERM (graceful termination request)
kill -9 <PID> # Sends SIGKILL (forceful termination, cannot be ignored)
- `pkill` / `killall`: Kill processes by name.
pkill firefox # Kills all processes named firefox
killall nginx # Kills all processes named nginx
- `jobs`: Lists background jobs in the current shell session.
# Run a command in background (append &)
./my_script.sh &
jobs # Show background jobs
# Output: [1]+ Running ./my_script.sh
- `fg` (Foreground): Brings a background job to the foreground.
fg %1 # Bring job 1 to foreground
- `bg` (Background): Sends a suspended job to the background. (Use Ctrl + z to suspend a foreground job first).
# Run a command, then press Ctrl+Z to suspend
sleep 60
^Z
# Output: [1]+ Stopped sleep 60
bg %1 # Send job 1 to background
11. Service Management (systemd)
Most modern Linux distributions (Ubuntu, Fedora, CentOS 7+, Debian 8+, Kali) use `systemd` as their init system and service manager. It controls system services (daemons).
- `systemctl status <service_name>`: Check the status of a service.
systemctl status nginx.service
# Output will show if it's active (running), inactive (dead), enabled (starts on boot), etc.
- `systemctl start <service_name>`: Start a service.
sudo systemctl start nginx.service
- `systemctl stop <service_name>`: Stop a service.
sudo systemctl stop nginx.service
- `systemctl restart <service_name>`: Restart a service.
sudo systemctl restart nginx.service
- `systemctl enable <service_name>`: Enable a service to start automatically on boot.
sudo systemctl enable nginx.service
- `systemctl disable <service_name>`: Disable a service from starting automatically on boot.
sudo systemctl disable nginx.service
- `systemctl reload <service_name>`: Reload a service's configuration without restarting (if supported by the service).
sudo systemctl reload nginx.service
- `systemctl list-units --type=service`: List all active services.
- `systemctl is-active <service_name>`: Check if a service is running.
12. Networking
Linux provides robust tools for network configuration and troubleshooting.
- `ip a` (IP Address): Displays network interface information (IP addresses, MAC addresses, link status). Recommended over `ifconfig`.
ip a
# Shows interfaces like lo (loopback), eth0 (Ethernet), wlan0 (Wireless)
- `ip route`: Displays the routing table.
ip route show
- `ping`: Tests network connectivity to a host.
ping google.com # Ping a domain
ping -c 4 192.168.1.1 # Ping an IP address 4 times
- `ss` (Socket Statistics): Displays network socket information. (Modern replacement for `netstat`).
ss -tuln # Show TCP/UDP listening ports
ss -tunap # Show all TCP/UDP connections with process info
- `netstat` (Legacy, use `ss`): Displays network connections, routing tables, interface statistics.
netstat -tulnp # Same as ss -tulnp
- `curl` / `wget`: Command-line tools for making web requests and downloading files.
curl https://example.com # Fetch content of a URL
wget https://example.com/file.zip # Download a file
- `nslookup` / `dig`: DNS lookup utilities.
nslookup google.com
dig example.com MX # Get mail exchange records
- `traceroute` / `tracepath`: Trace the route packets take to a network host.
traceroute google.com
- Network Configuration Files (common locations, managed by NetworkManager/systemd-networkd usually):
- `/etc/network/interfaces` (Debian/Ubuntu older style)
- `/etc/netplan/*.yaml` (Ubuntu modern)
- `/etc/sysconfig/network-scripts/` (Red Hat-based)
- `/etc/resolv.conf` (DNS resolver configuration)
13. Storage Management
Managing disk space, partitions, and file systems.
- `df` (Disk Free): Reports file system disk space usage.
df -h # Human-readable output (GB, MB)
- `du` (Disk Usage): Estimates file space usage of files and directories.
du -sh /home/yourusername # Summarize home directory size (human-readable)
du -h /var/log # Show sizes of subdirectories in /var/log
- `lsblk` (List Block Devices): Lists information about all available or specified block devices (hard drives, partitions).
lsblk
- `fdisk` (Partition Disk): Command-line utility for disk partitioning. (Use with extreme caution).
sudo fdisk /dev/sda # Opens interactive partitioning tool for sda
- `mkfs` (Make Filesystem): Builds a Linux file system on a device.
sudo mkfs.ext4 /dev/sdb1 # Format partition sdb1 with ext4 filesystem
- `mount` / `umount`: Mounts a file system onto a directory, making it accessible. `umount` unmounts it.
sudo mount /dev/sdb1 /mnt/data # Mount sdb1 to /mnt/data
sudo umount /mnt/data # Unmount /mnt/data
- `/etc/fstab`: A configuration file that defines static file systems to be mounted automatically at boot time.
- LVM (Logical Volume Manager): Provides a more flexible way to manage disk space, allowing you to create logical volumes that span multiple physical disks or partitions, and easily resize them. (More advanced topic).
14. Shell Scripting Basics
Shell scripting allows you to automate tasks by writing a series of commands in a file that the shell can execute.
A. Creating a Script:
# Create a file named 'hello.sh'
nano hello.sh
# Add the following content:
#!/bin/bash
# This is a simple shell script
echo "Hello from my first script!"
USERNAME=$(whoami) # Get current username
echo "You are running this script as: $USERNAME"
DATE=$(date +%Y-%m-%d) # Get current date
echo "Today's date is: $DATE"
B. Making Executable:
chmod +x hello.sh
C. Running the Script:
./hello.sh
# Output:
# Hello from my first script!
# You are running this script as: yourusername
# Today's date is: 2025-07-19 (or current date)
D. Basic Scripting Concepts:
15. Text Editors
You'll frequently use text editors in Linux, especially in the terminal.
16. Security Best Practices
Linux offers robust security features, but proper administration is key.
- Keep System Updated: Regularly update your OS and software to patch vulnerabilities.
sudo apt update && sudo apt upgrade -y
- Use Strong Passwords & MFA: For all user accounts, especially `root` or `sudo` users. Implement SSH key-based authentication instead of passwords where possible.
- Principle of Least Privilege: Grant users and services only the minimum permissions necessary to perform their tasks. Avoid using `root` for daily operations.
- Configure Firewall: Use a firewall (e.g., `ufw` on Ubuntu, `firewalld` on Fedora) to restrict network access.
sudo ufw enable # Enable firewall
sudo ufw allow ssh # Allow SSH (port 22)
sudo ufw allow http # Allow HTTP (port 80)
sudo ufw status verbose # Check status
- Disable Unnecessary Services: Stop and disable services you don't need to reduce the attack surface.
sudo systemctl disable <service_name>
- Monitor Logs: Regularly review system logs (`/var/log/syslog`, `/var/log/auth.log`) for suspicious activity. Use tools like `journalctl` (for systemd).
sudo journalctl -f # Follow live logs
sudo journalctl -u sshd # View SSH daemon logs
- Regular Backups: Implement a robust backup strategy for critical data.
- Secure SSH: Disable password authentication for SSH, use SSH keys, change default SSH port, and restrict root login.
- Audit File Permissions: Periodically review file and directory permissions to ensure they are set correctly.
Your Linux Journey Begins!
Linux is an incredibly powerful and versatile operating system. This tutorial provides a solid foundation for understanding its core components and essential commands. The best way to learn Linux is by doing. Set up a virtual machine, get comfortable with the terminal, and start experimenting. Don't be afraid to make mistakes; that's part of the learning process. The vast Linux community is always there to help you on your journey!