Linux Guide

A comprehensive Linux command-line guide โ€” filesystem navigation, permissions, processes, networking, shell scripting, and more. Every code block has a Copy button.

Copy button on each code block  ยท  โ— Beginner โ— Intermediate โ— Advanced

01 Introduction โ€” What is Linux?

Linux is an open-source operating system kernel that powers everything from servers and supercomputers to Android phones and embedded devices. Unlike Windows or macOS, Linux is highly customizable, secure, and free.

A Linux system is made of several layers:

Kernel
Core of the OS
โŸถ
Shell
Command interpreter
โŸถ
Utilities
Standard programs
โŸถ
Applications
User programs

Distributions (distros) are Linux packaged with a kernel, tools, and package manager. Popular ones include:

Key idea: In Linux, everything is a file โ€” hardware devices, processes, sockets, and regular files are all represented as files in the filesystem.

02 The Linux Filesystem Hierarchy Beginner

Linux uses a single rooted tree โ€” everything starts at / (the root directory). There are no drive letters like C:\.

/
Root โ€” top of the filesystem
/home
User home directories
/etc
Configuration files
/var
Variable data (logs, databases)
/usr
User programs & libraries
/bin
Essential user binaries
/sbin
System administration binaries
/tmp
Temporary files (cleared on boot)
/dev
Device files (hardware)
/proc
Process & kernel info (virtual)
/opt
Optional third-party software
/boot
Boot loader files & kernel
Tip: /proc and /sys are virtual filesystems โ€” they don't exist on disk but reflect kernel data structures. Reading them gives you real-time system info.

04 File & Directory Operations Beginner

โ–ถtouch Create an empty file
touch file.txt         # create empty file (or update timestamp)
touch file1.txt file2.txt  # create multiple files
โ–ถmkdir Create directories
mkdir myfolder          # create a directory
mkdir -p a/b/c          # create parent directories as needed
mkdir -m 755 secure     # create with specific permissions
โ–ถcp Copy files & directories
cp file.txt backup.txt             # copy file
cp -r myfolder backup               # copy directory recursively
cp -i file.txt /target/             # prompt before overwrite
cp -v file.txt /target/             # verbose output
cp -u file.txt /target/             # copy only if newer
โ–ถmv Move or rename
mv file.txt /new/location/         # move file
mv oldname.txt newname.txt          # rename file
mv -i file.txt /target/             # prompt before overwrite
mv -u file.txt /target/             # move only if newer
โ–ถrm Remove files & directories
rm file.txt                         # delete a file
rm -r myfolder                      # delete directory recursively
rm -f file.txt                      # force delete (no prompt)
rm -rf myfolder                     # โš  dangerous โ€” delete without confirmation

rm -rf / will delete your entire system. Double-check before running destructive commands!

โ–ถln Create links
ln -s /original/file link-name      # symbolic (soft) link
ln /original/file hard-link          # hard link (same inode)

Symbolic links are shortcuts. Hard links are additional names for the same file data โ€” deleting one keeps the other.

โš  Safety first: Use -i (interactive) with cp, mv, and rm when you're learning. It will ask before overwriting or deleting.

05 Permissions Intermediate

Linux uses a permission system with three levels: owner, group, and others. Each level has three rights: read (r), write (w), and execute (x).

# View permissions with ls -l
-rw-r--r--  1 alice developers  1024 Jun 15 10:00 file.txt
# ^^^^       ^               ^
# |owner    group           others
# rw- = read+write, r-- = read-only, r-x = read+execute
โ–ถchmod Change permissions
# Symbolic mode:
chmod u+x script.sh      # add execute for user (owner)
chmod g-w file.txt       # remove write for group
chmod o+r file.txt       # add read for others
chmod a+x script.sh      # add execute for everyone

# Numeric mode (octal):
chmod 755 script.sh      # rwxr-xr-x
chmod 644 file.txt       # rw-r--r--
chmod 700 private.sh     # rwx------

# Common values:
# 7 = rwx (read+write+execute)
# 6 = rw- (read+write)
# 5 = r-x (read+execute)
# 4 = r-- (read only)
# 0 = --- (no permissions)
โ–ถchown Change owner & group
sudo chown bob file.txt         # change owner to bob
sudo chown bob:devs file.txt    # change owner:group
sudo chown -R bob:devs mydir/   # recursive

Only root (using sudo) can change file ownership.

โ–ถchgrp Change group only
chgrp devs file.txt             # change group to devs
chgrp -R devs mydir/            # recursive
โ–ถumask Default permission mask
umask                          # show current mask (e.g., 0022)
umask 0027                     # set mask (more restrictive)

The umask subtracts permissions from the default (666 for files, 777 for directories). A umask of 022 means new files get 644 and new dirs get 755.

โ–ถls -l Special permissions (SUID, SGID, Sticky)
# SUID (set user ID) โ€” runs as file owner:
chmod u+s executable         # shown as 's' in owner's execute field

# SGID โ€” runs as group owner:
chmod g+s directory          # new files inherit group

# Sticky bit โ€” only owner can delete:
chmod +t /tmp                # shown as 't' in others' execute field

Sticky bit is used on /tmp โ€” anyone can write but only the file owner can delete their own files.

Permission check: To execute a script, you need r-x (read + execute). To list a directory, you need r-- (read). To enter a directory, you need --x (execute).

06 Process Management Intermediate

Every running program is a process with a unique PID (Process ID).

โ–ถps List processes
ps                       # processes in current shell
ps aux                   # all processes (BSD style)
ps -ef                   # all processes (standard style)
ps aux --sort=-%mem      # sorted by memory usage
ps aux --sort=-%cpu      # sorted by CPU usage
ps -u username           # processes of a specific user
โ–ถtop / htop Real-time process monitor
top                      # real-time view (press q to quit)
htop                     # prettier version (install first)

Inside top: press P to sort by CPU, M for memory, k to kill a process, q to quit.

โ–ถkill Send signals to processes
kill PID                 # gracefully terminate (SIGTERM, 15)
kill -9 PID              # force kill (SIGKILL, 9) โ€” immediate
kill -15 PID             # explicitly send SIGTERM
kill -2 PID              # interrupt (SIGINT, like Ctrl+C)
kill -1 PID              # hangup โ€” reload config (SIGHUP)
killall firefox          # kill all processes named firefox
pkill -f "pattern"       # kill by pattern match
โ–ถjobs / bg / fg Background & foreground
# Run a command in background:
long-command &

# Suspend current process:
# Press Ctrl+Z

jobs                     # list background jobs
bg %1                    # resume job 1 in background
fg %2                    # bring job 2 to foreground
โ–ถnohup / disown Keep processes running after logout
nohup long-command &     # ignore HUP signal
long-command & disown    # remove from shell job control
Process states: R (running), S (sleeping), D (uninterruptible sleep), Z (zombie), T (stopped).

07 Package Management Beginner

Package managers install, update, and remove software. Commands vary by distribution family.

Debian / Ubuntu (apt)

sudo apt update              # update package list
sudo apt upgrade             # upgrade all packages
sudo apt install firefox     # install a package
sudo apt remove firefox      # remove a package
sudo apt purge firefox       # remove package + config files
sudo apt autoremove          # remove unused dependencies
apt search keyword           # search for a package
apt show firefox             # show package details

Fedora / RHEL (dnf)

sudo dnf install firefox     # install
sudo dnf remove firefox      # remove
sudo dnf update              # update all
sudo dnf search keyword      # search
sudo dnf info firefox        # package info

Arch Linux (pacman)

sudo pacman -S firefox       # install
sudo pacman -R firefox       # remove
sudo pacman -Syu             # sync + upgrade (full update)
sudo pacman -Ss keyword      # search

Snap & Flatpak (universal)

sudo snap install firefox    # Snap package
flatpak install flathub org.mozilla.firefox  # Flatpak
Tip: Always run sudo apt update (or equivalent) before installing โ€” it refreshes the list of available packages and versions.

08 Networking Basics Intermediate

โ–ถip Modern network configuration
ip addr                  # show all network interfaces + IPs
ip a                     # shorthand
ip link                  # show interface status
ip route                 # show routing table
ip link set eth0 up      # bring interface up
ip link set eth0 down    # bring interface down
โ–ถping Test network connectivity
ping google.com          # ping until Ctrl+C
ping -c 4 google.com     # ping 4 times then stop
ping -4 8.8.8.8          # ping by IP (Google DNS)
โ–ถss Socket statistics
ss -tulpn                # show listening ports and processes
ss -tua                  # all TCP/UDP connections
ss -tuln                 # numeric ports only (no DNS)

Replaces the older netstat. Use -p to see which process owns each socket (requires sudo).

โ–ถcurl / wget Download & transfer data
curl https://example.com             # fetch webpage content
curl -O https://example.com/file.zip # download file
curl -o myfile.zip https://...        # download with custom name

wget https://example.com/file.zip     # download file
wget -c https://...                   # resume interrupted download
wget -r https://example.com           # recursive download
โ–ถssh Remote login
ssh user@192.168.1.100               # connect to remote machine
ssh -p 2222 user@host                 # custom port
ssh -i ~/.ssh/id_rsa user@host        # use specific key
ssh -J jump@gateway user@target       # via jump host
โ–ถscp Secure copy (over SSH)
scp file.txt user@host:/remote/path/     # copy to remote
scp user@host:/remote/file.txt .         # copy from remote
scp -r myfolder/ user@host:/path/        # recursive directory copy
Common ports: 22 (SSH), 80 (HTTP), 443 (HTTPS), 3306 (MySQL), 5432 (PostgreSQL), 8080 (alternative HTTP).

09 Text Editors in the Terminal Beginner

You'll often need to edit files directly in the terminal. Here are the most common editors:

โ–ถnano Beginner-friendly (start here)
nano file.txt            # open file
# Ctrl+O  โ†’ Save (write out)
# Ctrl+X  โ†’ Exit
# Ctrl+W  โ†’ Search
# Ctrl+K  โ†’ Cut line
# Ctrl+U  โ†’ Paste line
# Ctrl+G  โ†’ Help

Nano shows available commands at the bottom of the screen. ^ means the Ctrl key.

โ–ถvim Powerful & ubiquitous
vim file.txt             # open file

# Modes:
# Normal โ€” press Esc to get here
# Insert โ€” press i to enter
# Visual โ€” press v to select text
# Command โ€” press : to type commands

# Essential commands (in Normal mode):
i              # enter Insert mode
:w             # save file
:q             # quit
:wq            # save and quit
:q!            # quit without saving
/pattern       # search for "pattern"
dd             # delete (cut) current line
yy             # yank (copy) current line
p              # paste below
u              # undo
Ctrl+r         # redo

Vim has a steep learning curve but is incredibly efficient. Run vimtutor for a built-in 30-minute tutorial.

โ–ถVS Code Graphical editor (GUI)
code file.txt            # open file in VS Code
code .                   # open current directory

Not terminal-based but invaluable for larger projects. Install via your package manager.

10 Shell Basics & Shortcuts Beginner

The shell is your command interpreter. Bash is the most common one. Here are essential tricks:

Wildcards (globbing)

# * matches any characters
ls *.txt                 # all .txt files
rm *.log                 # delete all .log files

# ? matches exactly one character
ls file?.txt             # file1.txt, fileA.txt, but not file10.txt

# [] matches a set of characters
ls file[0-9].txt         # file0.txt through file9.txt
ls [abc]*.txt            # files starting with a, b, or c

Redirection & pipes

# Redirect output to a file (overwrite)
echo "Hello" > file.txt

# Append to a file
echo "More" >> file.txt

# Redirect errors
command 2> error.log

# Pipe: send output of one command as input to another
ls -la | grep ".txt"               # filter list
ps aux | grep firefox              # find process
dmesg | tail -20                   # last 20 kernel messages
cat file.txt | wc -l               # count lines

Command chaining

# && โ€” run next only if previous succeeds
mkdir project && cd project && git init

# || โ€” run next only if previous fails
cd /nonexistent || echo "Directory not found"

# ; โ€” run sequentially regardless
echo "start" ; echo "middle" ; echo "end"

Command history

history                  # show command history
!!                       # repeat last command
!100                     # repeat command #100 from history
Ctrl+r                   # search history (type to filter)
!$                       # last argument of previous command
!ls                      # repeat last ls command

Useful shortcuts

Ctrl+C
Kill current command
Ctrl+D
Exit shell / EOF
Ctrl+Z
Suspend (background)
Ctrl+L
Clear screen
Ctrl+A
Go to start of line
Ctrl+E
Go to end of line
Ctrl+W
Delete word backward
Tab
Auto-complete
Tab completion is your best friend: Press Tab to auto-complete file names, commands, and paths. Press twice to see all matches.

11 Users & Groups Intermediate

โ–ถwhoami / id Who are you?
whoami                   # current username
id                       # uid, gid, groups
id username              # info about another user
โ–ถuseradd / usermod / userdel Manage users
sudo useradd -m newuser         # create user with home dir
sudo passwd newuser             # set password
sudo usermod -aG sudo newuser   # add to sudo group
sudo usermod -L username        # lock account
sudo userdel -r username        # delete user + home dir
โ–ถgroupadd / groupmod / groupdel Manage groups
sudo groupadd developers        # create group
sudo groupmod -n newname oldname # rename group
sudo groupdel developers         # delete group
sudo usermod -aG groupname user  # add user to group
groups username                  # list user's groups
โ–ถsudo Run commands as root
sudo command               # run as root
sudo -i                    # open root shell
sudo -u user command        # run as another user
sudo -l                    # list allowed commands

Use sudo sparingly โ€” only when a command needs elevated privileges. Running everything as root is dangerous.

โš  Root safety: Never log in as root for daily work. Use sudo for specific commands. One typo as root can break the system.

12 Storage, Disks & Filesystems Advanced

โ–ถdf Disk free space
df -h                    # human-readable disk usage
df -h /home              # usage for a specific mount
df -T                    # show filesystem type
โ–ถdu Directory/file size
du -sh myfolder          # total size of folder
du -sh *                 # size of each item in current dir
du -h --max-depth=1      # show sizes one level deep
du -ah myfolder          # show every file's size
โ–ถlsblk / blkid List block devices
lsblk                    # show disks and partitions
lsblk -f                 # show filesystem info
blkid                    # show UUIDs and labels
โ–ถmount / umount Attach & detach filesystems
mount                    # show all mounted filesystems
sudo mount /dev/sdb1 /mnt/usb    # mount a drive
sudo umount /mnt/usb              # unmount
sudo mount -t tmpfs tmpfs /mnt/ram  # RAM disk (in memory)
โ–ถfdisk / parted Partition disks
sudo fdisk -l             # list all partitions
sudo fdisk /dev/sda       # interactively partition
sudo parted /dev/sda      # modern partition tool

โš  Warning: Repartitioning can destroy your data. Only do this on empty or backed-up drives.

UUIDs are forever: Use blkid to find a drive's UUID, then reference it in /etc/fstab for reliable mounting โ€” unlike device names (/dev/sda1), UUIDs never change.

13 System Information Beginner

# System & hardware
uname -a                 # all system info (kernel, arch, hostname)
uname -r                 # kernel release
hostname                 # system hostname
uptime                   # how long the system has been running
who                      # who is logged in
# Memory
free -h                  # RAM + swap usage (human-readable)
free -m                  # in MB
vmstat 1                 # continuous memory/proc stats
# CPU
lscpu                    # CPU architecture info
nproc                    # number of CPU cores
# Hardware (requires lshw or dmidecode)
sudo lshw                # full hardware details
sudo dmidecode           # DMI/BIOS info
lsusb                    # USB devices
lspci                    # PCI devices
# Date & time
date                     # current date/time
cal                      # calendar of current month
timedatectl              # system time settings
# Logs
journalctl               # view systemd logs
journalctl -u ssh        # logs for a specific service
journalctl -f            # follow logs in real time
journalctl --since yesterday  # logs since yesterday
Tip: Use watch -n 2 'command' to run any command every 2 seconds โ€” great for monitoring: watch -n 1 'free -h'

14 Shell Scripting Basics Intermediate

Shell scripts let you automate repetitive tasks. A script is just a file with commands.

Your first script

#!/bin/bash
# This is a comment. The line above is the shebang โ€” tells the system this is a Bash script.

echo "Hello, World!"

# Variables (no spaces around =):
name="Laksh"
echo "Hello, $name"

# Read user input:
echo "Enter your name:"
read username
echo "Welcome, $username"

# Exit with a status:
exit 0

Run a script

chmod +x script.sh       # make executable
./script.sh              # run it
bash script.sh           # or run with Bash directly

Conditionals & loops

# If/else
if [ -f "$file" ]; then
    echo "$file exists"
elif [ -d "$dir" ]; then
    echo "$dir is a directory"
else
    echo "Not found"
fi

# For loop
for file in *.txt; do
    echo "Processing $file"
done

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

Useful test operators

[ -f "$file" ]
Is a regular file?
[ -d "$dir" ]
Is a directory?
[ -e "$path" ]
Does path exist?
[ -z "$var" ]
Is variable empty?
[ -n "$var" ]
Is variable non-empty?
[ "$a" = "$b" ]
String equals
[ $n -gt 5 ]
Number greater than
Always quote variables: Use "$var" not $var. Quoting prevents errors if the variable contains spaces or is empty.

15 Security Basics Intermediate

โ–ถufw Firewall (Uncomplicated Firewall)
sudo ufw status             # check status
sudo ufw enable              # turn on firewall
sudo ufw default deny        # deny incoming by default
sudo ufw allow 22/tcp        # allow SSH
sudo ufw allow 80/tcp        # allow HTTP
sudo ufw allow 443/tcp       # allow HTTPS
sudo ufw deny 23/tcp         # deny telnet
sudo ufw delete allow 80     # remove a rule
โ–ถfail2ban Block brute-force attacks
sudo apt install fail2ban
sudo systemctl enable fail2ban --now

# Configuration: /etc/fail2ban/jail.local
# It monitors SSH logs and bans IPs after 5 failed attempts
โ–ถopenssl Generate keys & certificates
# Generate a private key
openssl genrsa -out key.pem 2048

# Generate a self-signed certificate
openssl req -new -x509 -key key.pem -out cert.pem -days 365

# View certificate info
openssl x509 -in cert.pem -text -noout
โ–ถgpg Encrypt & sign files
gpg --gen-key                     # generate a key pair
gpg -c file.txt                   # symmetric encryption (password)
gpg -e -r recipient file.txt       # encrypt for a recipient
gpg -d file.txt.gpg               # decrypt
โ–ถchkrootkit / rkhunter Rootkit detection
sudo apt install chkrootkit rkhunter
sudo chkrootkit
sudo rkhunter --check
โš  Security rule #1: Keep your system updated: sudo apt update && sudo apt upgrade (or equivalent). Most attacks exploit known vulnerabilities with available patches.

16 Quick Command Reference

Keep this section bookmarked โ€” it covers 90% of daily Linux tasks.

File Operations

ls -la
List all files with details
cd /path
Change directory
pwd
Print working directory
cp -r src dst
Copy recursively
mv old new
Move or rename
rm -rf dir
โš  Delete directory
mkdir -p a/b/c
Create nested dirs
touch file
Create empty file

Viewing & Editing

cat file
Print file content
less file
Paginated view (q to quit)
head -20 file
First 20 lines
tail -f file
Follow file (logs)
nano file
Simple editor
vim file
Powerful editor
grep pattern file
Search for pattern
sed 's/old/new/g' file
Find & replace

Permissions & Ownership

chmod 755 file
Set rwxr-xr-x
chown user:group file
Change owner:group
chgrp group file
Change group
umask 022
Default permissions mask

Process Management

ps aux
All processes
top / htop
Real-time monitor
kill -9 PID
Force kill
killall name
Kill by name
command &
Run in background
nohup command &
Run after logout

Network

ip a
Show IP addresses
ping -c 4 host
Test connectivity
ss -tulpn
Listening ports
curl -O url
Download file
ssh user@host
Remote login
scp file host:
Copy over SSH

System

uname -a
Full system info
free -h
Memory usage
df -h
Disk space
du -sh *
Directory sizes
journalctl -xe
System logs
systemctl status svc
Service status

Package Management

apt install pkg
Debian/Ubuntu install
dnf install pkg
Fedora/RHEL install
pacman -S pkg
Arch install
Remember: Most commands have a --help flag or a manual page: man <command>. Press q to exit the manual.