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 โ Advanced01 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:
Core of the OS
Command interpreter
Standard programs
User programs
Distributions (distros) are Linux packaged with a kernel, tools, and package manager. Popular ones include:
- Ubuntu โ beginner-friendly, Debian-based
- Fedora โ cutting-edge, Red Hat-based
- Debian โ rock-stable, server favorite
- Arch โ DIY, rolling release
- CentOS / Rocky Linux โ enterprise servers
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:\.
/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.
-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.
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
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
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
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
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.
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.
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
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
"$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
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
Viewing & Editing
Permissions & Ownership
Process Management
Network
System
Package Management
--help flag or a manual page: man <command>. Press q to exit the manual.