Linux is a Unix-like, open-source operating system kernel first released by Linus Torvalds in 1991. When combined with GNU utilities and other software, it forms complete operating systems (distributions) like Ubuntu, Debian, Fedora, and Arch Linux. Linux dominates the server market, powers most of the internet’s infrastructure, and is the foundation for Android and countless embedded systems.

See also: Systemd, Command Line (CLI), Containers, Kubernetes

File System Hierarchy

The Filesystem Hierarchy Standard (FHS) defines the directory structure on Linux systems.

DirectoryPurpose
/Root filesystem, contains everything
/binEssential user binaries (ls, cp, cat)
/sbinEssential system binaries (init, fsck, mount)
/etcHost-specific configuration files
/homeUser home directories
/rootHome directory for root user
/varVariable data (logs, mail, spool, cache)
/var/logLog files
/tmpTemporary files (cleared on reboot)
/usrSecondary hierarchy for read-only user data
/usr/binMost user commands
/usr/libLibraries for /usr/bin and /usr/sbin
/usr/localLocally installed software
/optOptional/third-party application packages
/libEssential shared libraries and kernel modules
/devDevice files (everything is a file)
/procVirtual filesystem for process and kernel info
/sysVirtual filesystem for device and driver info
/mntTemporary mount point
/mediaMount point for removable media
/bootBoot loader files and kernel
/srvData for services provided by the system

Process Management

Understanding Processes

Every running program is a process with a unique PID (Process ID). Processes have a parent-child relationship forming a tree structure, with PID 1 (init/systemd) at the root.

fork()

The fork system call clones the current process to create a new process. It creates a new process (the child process) by duplicating the state of the existing process with a few minor differences. The child process does not start from main. Instead it returns from fork() just as the parent process does.

After fork(), the parent receives the child’s PID while the child receives 0. This is how each process knows its role:

pid_t pid = fork();
if (pid == 0) {
    // Child process
} else {
    // Parent process (pid contains child's PID)
}

Process Commands

CommandDescription
ps auxList all processes with detailed info
ps -efList all processes in full format
topInteractive real-time process viewer
htopImproved interactive process viewer (needs install)
pgrep <name>Find PIDs by process name
pidof <name>Find PID of a running program
kill <pid>Send signal to process (default: SIGTERM)
kill -9 <pid>Force kill (SIGKILL, cannot be caught)
killall <name>Kill all processes by name
pkill <pattern>Kill processes matching pattern
nice -n 10 cmdRun command with adjusted priority
renice -n 5 -p <pid>Change priority of running process
nohup cmd &Run command immune to hangups
jobsList background jobs
fg %1Bring job 1 to foreground
bg %1Resume job 1 in background

Nice values range from -20 (highest priority) to 19 (lowest). Only root can set negative nice values.

Common Signals

SignalNumberDescription
SIGHUP1Hangup (often used to reload config)
SIGINT2Interrupt (Ctrl+C)
SIGKILL9Force kill (cannot be caught)
SIGTERM15Graceful termination (default)
SIGSTOP19Pause process (cannot be caught)
SIGCONT18Resume paused process

Users and Permissions

User Management

CommandDescription
whoamiDisplay current username
idDisplay user and group IDs
whoShow who is logged in
useradd <user>Create new user
usermod -aG <group> <user>Add user to group
userdel <user>Delete user
passwd <user>Change password
su - <user>Switch user with login shell
sudo <cmd>Run command as root
visudoEdit sudoers file safely

File Permissions

Permissions are represented as rwxrwxrwx (read, write, execute) for owner, group, and others.

-rwxr-xr-x 1 user group 4096 Jan 24 12:00 file.sh
│└┬┘└┬┘└┬┘
│ │  │  └── Others: r-x (read + execute)
│ │  └───── Group: r-x (read + execute)
│ └──────── Owner: rwx (read + write + execute)
└────────── File type (- = file, d = directory, l = symlink)
CommandDescription
chmod 755 fileSet permissions using octal (rwxr-xr-x)
chmod u+x fileAdd execute permission for owner
chmod g-w fileRemove write permission for group
chmod o=r fileSet others permission to read only
chmod -R 644 dir/Recursively set permissions
chown user:group fileChange owner and group
chown -R user dir/Recursively change owner
chgrp group fileChange group

Octal permission values: r=4, w=2, x=1 (e.g., 755 = rwxr-xr-x)

Special Permissions

PermissionOctalDescription
setuid4000Execute as file owner
setgid2000Execute as group owner / inherit directory group
sticky bit1000Only owner can delete files (common on /tmp)

Package Management

Debian/Ubuntu (apt)

apt update                 # Update package lists
apt upgrade                # Upgrade installed packages
apt install <package>      # Install package
apt remove <package>       # Remove package
apt search <term>          # Search packages
apt show <package>         # Show package details
apt autoremove             # Remove unused dependencies

RHEL/Fedora (dnf/yum)

dnf update                 # Update all packages
dnf install <package>      # Install package
dnf remove <package>       # Remove package
dnf search <term>          # Search packages
dnf info <package>         # Show package details

Arch Linux (pacman)

pacman -Syu                # Sync and upgrade
pacman -S <package>        # Install package
pacman -R <package>        # Remove package
pacman -Ss <term>          # Search packages
pacman -Qi <package>       # Query installed package info

Essential Commands

CommandDescription
pwdPrint working directory
cd <dir>Change directory
cd -Go to previous directory
ls -laList all files with details
ls -lhHuman-readable file sizes
mkdir -p a/b/cCreate nested directories
cp -r src/ dest/Copy directory recursively
mv old newMove/rename files
rm -rf dir/Remove directory recursively (careful!)
ln -s target linkCreate symbolic link
touch fileCreate empty file / update timestamp

File Content

CommandDescription
cat fileDisplay file contents
less fileView file with pagination
head -n 20 fileFirst 20 lines
tail -n 20 fileLast 20 lines
tail -f fileFollow file (live updates)
wc -l fileCount lines

Searching

CommandDescription
grep pattern fileSearch for pattern in file
grep -r pattern dir/Recursive search in directory
grep -i patternCase-insensitive search
grep -v patternInvert match (exclude)
grep -E 'regex'Extended regex (egrep)
find . -name "*.txt"Find files by name
find . -type f -mtime -7Files modified in last 7 days
find . -size +100MFiles larger than 100MB
locate filenameFast search using database

Text Processing

CommandDescription
awk '{print $1}'Print first column
awk -F: '{print $1}'Use : as delimiter
sed 's/old/new/g'Replace all occurrences
sed -i 's/old/new/g' fileIn-place replacement
cut -d: -f1Cut first field, delimiter :
sortSort lines
sort -uSort and remove duplicates
uniqRemove adjacent duplicates
tr 'a-z' 'A-Z'Translate characters

xargs

Build and execute commands from stdin:

find . -name "*.log" | xargs rm           # Delete found files
cat urls.txt | xargs -n1 curl             # Curl each URL
find . -name "*.txt" | xargs -I {} cp {} backup/   # Copy with placeholder

Shell Basics

Bash Configuration Files

FilePurpose
/etc/profileSystem-wide login shell config
~/.bash_profileUser login shell config
~/.bashrcUser interactive non-login shell config
~/.bash_logoutExecuted on logout

Environment Variables

export VAR="value"       # Set variable for current session and child processes
echo $VAR                # Access variable
env                      # List all environment variables
printenv VAR             # Print specific variable
unset VAR                # Remove variable

Important Environment Variables

VariableDescription
PATHDirectories to search for executables
HOMEUser’s home directory
USERCurrent username
SHELLCurrent shell
PWDCurrent working directory
EDITORDefault text editor
LANGSystem locale

PATH

The PATH variable contains colon-separated directories where the shell looks for executables:

echo $PATH
# /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
 
# Add directory to PATH
export PATH="$HOME/bin:$PATH"

Useful Shell Features

!!                       # Repeat last command
!$                       # Last argument of previous command
Ctrl+R                   # Reverse search history
Ctrl+L                   # Clear screen
Ctrl+A / Ctrl+E          # Start / end of line
Ctrl+U / Ctrl+K          # Delete to start / end of line

Networking Commands

CommandDescription
ip addrShow IP addresses
ip linkShow network interfaces
ip routeShow routing table
ss -tulnShow listening TCP/UDP ports
ss -tpShow TCP connections with process
netstat -tulnShow listening ports (legacy)
curl -I urlFetch HTTP headers
curl -X POST -d 'data' urlPOST request
wget urlDownload file
dig domainDNS lookup
nslookup domainDNS lookup (legacy)
host domainDNS lookup (simple)
ping hostTest connectivity
traceroute hostTrace packet route
mtr hostCombined ping and traceroute
nc -zv host portTest TCP port connectivity

Firewall (iptables/nftables)

Modern systems use nftables, but many still use iptables:

iptables -L              # List rules
iptables -A INPUT -p tcp --dport 22 -j ACCEPT  # Allow SSH
ufw status               # Ubuntu firewall status
ufw allow 22             # Allow port 22

Service Management

Most modern Linux distributions use Systemd for service management:

systemctl status nginx        # Check service status
systemctl start nginx         # Start service
systemctl stop nginx          # Stop service
systemctl restart nginx       # Restart service
systemctl enable nginx        # Start on boot
systemctl disable nginx       # Don't start on boot
systemctl daemon-reload       # Reload unit files after changes
journalctl -u nginx           # View service logs
journalctl -fu nginx          # Follow service logs

Useful Developer Tools

ToolDescription
htopInteractive process viewer
tmux / screenTerminal multiplexers
ripgrep (rg)Fast recursive grep
fdFast, user-friendly find
fzfFuzzy finder
batCat with syntax highlighting
jqJSON processor
yqYAML processor
ncduDisk usage analyser
treeDirectory tree visualisation
watchRun command repeatedly
straceTrace system calls
lsofList open files
lsof -i :8080Find process using port

Common Tasks

Disk Usage

df -h                    # Filesystem disk space
du -sh *                 # Size of items in current directory
du -sh */ | sort -h      # Sorted directory sizes
ncdu                     # Interactive disk usage

Logs

journalctl -xe           # Recent systemd logs with context
dmesg                    # Kernel ring buffer
tail -f /var/log/syslog  # Follow syslog

Compression

tar -czvf archive.tar.gz dir/    # Create gzipped tarball
tar -xzvf archive.tar.gz         # Extract gzipped tarball
tar -cjvf archive.tar.bz2 dir/   # Create bzip2 tarball
zip -r archive.zip dir/          # Create zip
unzip archive.zip                # Extract zip

Resources