🐧

Top 50 Linux / Shell Scripting Interview Questions & Answers (2026)

50 Questions 20 Beginner 20 Intermediate 10 Advanced

About Linux / Shell Scripting

Top 50 Linux and Shell Scripting interview questions covering file system, process management, bash scripting, networking, and system administration. Companies hiring for Linux / Shell Scripting roles test this knowledge at every stage — from first-round screens that check the basics to final-round conversations about real-world trade-offs.

What to Expect in a Linux / Shell Scripting Interview

Expect a mix of conceptual and practical Linux / Shell Scripting questions: clear definitions and core-concept checks for junior roles, hands-on scenario questions for mid-level roles, and architecture or trade-off discussions for senior roles. Interviewers usually move from foundational topics toward the kind of problems you'd actually face on the job.

How to Use This Guide

Work through the Linux / Shell Scripting questions in order — Beginner, then Intermediate, then Advanced — so each concept builds on the last. Every question has its own page; bookmark the ones that trip you up and revisit them the day before your interview.

Curated by Tech Baithak Editorial Team  ·  Last updated: June 2026

Beginner 20 questions

Core concepts every Linux / Shell Scripting developer must know.

01

What do the ls, cd, pwd, mkdir, rm, cp, and mv commands do?

These are the fundamental Linux file-system commands. ls lists directory contents (ls -la shows hidden files and details). cd path changes the current directory; cd .. moves up one level. pwd prints the current working directory. mkdir dir creates a new directory (mkdir -p a/b/c creates nested directories). rm file removes a file; rm -rf dir recursively deletes a directory — use with caution. cp src dst copies a file or directory (-r for directories). mv src dst moves or renames a file. Mastering these commands is the foundation of Linux navigation and file management.

Open this question on its own page
02

What are cat, less, and more used for?

cat file concatenates and prints the full contents of a file to stdout — ideal for short files or combining multiple files (cat a.txt b.txt > combined.txt). more file is a pager that displays content one screen at a time — press Space to advance and q to quit; it only scrolls forward. less file is an improved pager that supports both forward and backward navigation with arrow keys and Page Up/Down. less also supports searching with /pattern and does not load the entire file into memory, making it suitable for very large log files.

Open this question on its own page
03

How does grep work for searching text?

grep pattern file searches for lines matching a regular expression pattern and prints matching lines. Key flags: -i (case-insensitive), -r (recursive directory search), -n (show line numbers), -v (invert match — show non-matching lines), -c (count matching lines), -l (list only file names), -E (extended regex, same as egrep). Example: grep -rn "TODO" ./src/ finds all TODOs in a codebase. Pipe output: dmesg | grep -i error filters kernel messages for errors. grep is one of the most frequently used Linux commands in daily sysadmin and development work.

Open this question on its own page
04

How does the find command work?

find path [options] [expression] searches for files and directories matching given criteria. Common options: -name "*.log" (by filename pattern), -type f (files only) or -type d (directories only), -mtime -7 (modified in last 7 days), -size +100M (larger than 100 MB), -user alice (owned by user). Execute a command on each result with -exec rm {} \; or pass results to another command with -print0 | xargs -0. Example: find /var/log -name "*.log" -mtime +30 -delete removes log files older than 30 days.

Open this question on its own page
05

How do chmod and chown control file permissions?

Linux file permissions are divided into three groups: owner, group, and others, each with read (4), write (2), and execute (1) bits. chmod 755 file sets owner=rwx(7), group=rx(5), others=rx(5). Symbolic form: chmod u+x file adds execute for the owner. chmod -R 644 ./dir applies recursively. chown user:group file changes the owner and group of a file. chown -R www-data:www-data /var/www recursively reassigns a web root. Use ls -l to inspect permissions — the output format is -rwxr-xr-x. Understanding permissions is critical for security and avoiding "permission denied" errors.

Open this question on its own page
06

How do ps and kill work for process management?

ps lists running processes. ps aux shows all processes for all users with CPU/memory usage, PID, and command. ps -ef shows a full-format listing. Filter with ps aux | grep nginx. kill PID sends SIGTERM (15) to gracefully stop a process, giving it time to clean up. kill -9 PID sends SIGKILL — an immediate, forceful termination the process cannot catch or ignore. kill -l lists all available signals. Use pkill processname to kill by name and killall processname to kill all instances. Always prefer SIGTERM first and resort to SIGKILL only if the process does not respond.

Open this question on its own page
07

How do df and du help with disk usage?

df (disk free) reports filesystem-level disk space: total, used, and available. df -h shows human-readable sizes (GB, MB). df -hT also shows filesystem types. du (disk usage) shows the space consumed by files and directories. du -sh /var/log shows the total size of the log directory. du -sh * | sort -h in a directory lists and sorts all items by size — great for finding what is consuming the most space. A common sysadmin task when a disk fills up: df -h to find the full filesystem, then du -sh /* and drilling down to locate the large files.

Open this question on its own page
08

What is top or htop and how do you use it?

top is an interactive real-time process monitor showing CPU usage, memory usage, load average, and a list of running processes sorted by CPU consumption. Key interactions: press M to sort by memory, P for CPU, k then a PID to kill a process, q to quit. htop is an improved alternative with a color interface, mouse support, and horizontal scrolling for wide process information. Both show system load averages (1, 5, 15 minutes) — a load average above the number of CPU cores indicates the system is overloaded. Install htop with sudo apt install htop or sudo yum install htop.

Open this question on its own page
09

How does SSH work and what are its basic usage patterns?

SSH (Secure Shell) provides encrypted remote login over an untrusted network. Basic usage: ssh user@host connects to a remote server. ssh -p 2222 user@host uses a non-default port. SSH supports two authentication methods: password-based and key-based. For key-based auth, generate a key pair with ssh-keygen -t ed25519 and copy the public key to the server with ssh-copy-id user@host. Configuration in ~/.ssh/config lets you define aliases: Host myserver then ssh myserver. Use ssh -L 8080:localhost:3000 user@host for local port forwarding (tunneling). Key-based auth is more secure than passwords and should always be preferred for production servers.

Open this question on its own page
10

What is the pipe (|) operator in Linux?

The pipe operator | connects the standard output (stdout) of one command to the standard input (stdin) of the next, creating a processing pipeline. This is the Unix philosophy of composing small, single-purpose tools. Examples: ps aux | grep nginx (filter process list), cat access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -10 (find the top 10 IP addresses in a web log). Pipes are buffered and run concurrently — the left command produces output as the right command consumes it, making pipelines efficient even on large data streams without loading everything into memory.

Open this question on its own page
11

What is the difference between > and >> for output redirection?

In Linux shell, > redirects stdout to a file, overwriting the file if it already exists (or creating it): echo "hello" > file.txt. >> redirects stdout and appends to the file, preserving existing content: echo "world" >> file.txt. To redirect stderr (file descriptor 2) as well: command > out.txt 2>&1 redirects both stdout and stderr to the same file. command 2> errors.txt captures only errors. /dev/null is a special device that discards all input: command > /dev/null 2>&1 silences all output from a command.

Open this question on its own page
12

What are man pages and how do you use them?

man command opens the manual page for a command — the authoritative reference for every option and behavior. Navigate with arrow keys or Page Up/Down, search with /pattern, and quit with q. Man pages are organized into sections: 1 (user commands), 2 (system calls), 3 (C library functions), 5 (file formats), 8 (sysadmin commands). Access a specific section with man 5 passwd. If you don't know the exact command name, use man -k keyword (or apropos keyword) to search descriptions. tldr command (from the tldr-pages project) offers practical examples as a quick alternative to the full man page.

Open this question on its own page
13

What are which and whereis used for?

which command shows the full path of the executable that will be run when you type a command in your shell, by searching the directories in $PATH: which python3 might return /usr/bin/python3. It only returns the first match — useful for checking which version of a tool is active. whereis command is broader — it searches for the binary, source code, and man page: whereis python3 returns all locations found in standard system directories. Use type command in bash for a more comprehensive answer that also identifies shell built-ins, aliases, and functions vs external binaries.

Open this question on its own page
14

How do echo and printf work in bash?

echo text prints text to stdout followed by a newline. Use echo -n to suppress the trailing newline and echo -e to interpret escape sequences like \n (newline) and \t (tab). printf is more powerful and portable — it uses C-style format strings: printf "Name: %s, Age: %d\n" "Alice" 30. printf does not add a newline automatically. printf is preferred in scripts because echo's behavior with options and escape sequences varies between shells and implementations. Always quote variables in echo to prevent word splitting: echo "$var" not echo $var.

Open this question on its own page
15

What does the file command do and what is stat?

file filename determines and displays the type of a file by examining its content (magic bytes), not just its extension. It correctly identifies scripts, executables, images, compressed archives, and text files: file script.shBourne-Again shell script, ASCII text executable. This is valuable when file extensions are missing or misleading. stat filename displays detailed inode information: file size in bytes, number of blocks, permissions in octal, owner/group UID/GID, inode number, number of hard links, and all three timestamps — access time (atime), modification time (mtime, when content changed), and change time (ctime, when metadata changed).

Open this question on its own page
16

How do head and tail work for viewing file portions?

head file prints the first 10 lines of a file. Use head -n 50 file to specify the number of lines. tail file prints the last 10 lines. tail -n 100 file shows the last 100 lines. The most important option is tail -f file which follows the file — it continuously outputs new lines as they are appended, making it essential for monitoring live log files: tail -f /var/log/nginx/access.log. Combine tail -f with grep: tail -f app.log | grep ERROR. head and tail can also be chained to extract a range: head -100 file | tail -50 extracts lines 51–100.

Open this question on its own page
17

How does wc (word count) work?

wc (word count) counts lines, words, and bytes in a file or stdin. wc file outputs three numbers: line count, word count, and byte count. Use specific flags to get only one: wc -l file (lines only — very common for counting results), wc -w file (words only), wc -c file (bytes), wc -m file (characters, different from bytes for multi-byte encodings). Piping is common: ls | wc -l counts files in a directory, grep -c pattern file counts matching lines (more efficient than grep | wc -l). wc is a simple but frequently used tool in shell pipelines.

Open this question on its own page
18

How do sort and uniq work together?

sort file sorts lines alphabetically by default. Key options: -n (numeric sort), -r (reverse), -k 2 (sort by the second field), -t: (use colon as field delimiter), -u (output unique lines only). uniq removes or reports adjacent duplicate lines — it only detects consecutive duplicates, so always pipe through sort first: sort file | uniq. uniq -c prefixes each line with its occurrence count — combined with sort -rn this gives you a frequency table: awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -20 shows the 20 most frequent IP addresses.

Open this question on its own page
19

How does tar work for archiving?

tar creates and extracts archives (originally "tape archive"). The most common operations: tar -czf archive.tar.gz directory/ creates a gzip-compressed archive (c=create, z=gzip, f=file). tar -xzf archive.tar.gz extracts a gzip archive (x=extract). tar -cjf archive.tar.bz2 dir/ uses bzip2 (better compression, slower). tar -xf archive.tar.gz -C /target/ extracts to a specific directory. tar -tzf archive.tar.gz lists contents without extracting. A common mnemonic for flags: create, extract, verbose (show files), z (gzip), f (filename follows). tar is the standard archiving tool on Linux for backups and software distribution.

Open this question on its own page
20

What are environment variables and how do you use $PATH and $HOME?

Environment variables are named values that are inherited by child processes and configure program behavior. $HOME holds the current user's home directory (/home/alice). $PATH is a colon-separated list of directories the shell searches for executables when you type a command — if a program isn't in any $PATH directory, the shell reports "command not found." View all variables with env or printenv. Set a variable: export MY_VAR="value" (makes it available to child processes). Add to PATH permanently: add export PATH="$PATH:/new/dir" to ~/.bashrc or ~/.profile. Per-command variables: DEBUG=1 ./myapp sets the variable only for that invocation.

Open this question on its own page
Intermediate 20 questions

Practical knowledge for developers with hands-on experience.

01

How does awk work for text processing?

awk is a pattern-scanning and processing language. It reads input line by line, splits each line into fields ($1, $2, ...; $0 = whole line) using whitespace or a custom delimiter (-F: for colon), and applies rules of the form pattern { action }. Examples: awk '{print $2}' file prints the second field of every line. awk -F: '{print $1}' /etc/passwd prints all usernames. awk '$3 > 100 {print $1, $3}' data filters and formats. awk 'BEGIN{sum=0} {sum+=$1} END{print sum}' numbers sums a column. awk is the tool of choice for structured tabular data processing in shell pipelines, far more powerful than basic cut or grep.

Open this question on its own page
02

How does sed work for stream editing?

sed (stream editor) applies editing commands to each line of input. The most common usage is substitution: sed 's/old/new/g' file replaces all occurrences of "old" with "new" (g = global; without it, only the first occurrence per line is replaced). sed -i 's/foo/bar/g' file.txt edits the file in-place. sed -n '10,20p' file prints only lines 10 through 20. sed '/^#/d' config deletes comment lines. sed 's/^/ /' file indents every line. sed supports full regular expressions and multiple commands with -e. It is indispensable for automated text transformation in CI/CD pipelines and configuration management scripts.

Open this question on its own page
03

How does cron work and how do you edit crontabs?

cron is the Linux task scheduler that runs commands on a defined time schedule. Edit the user's crontab with crontab -e; list it with crontab -l. Each cron entry has five time fields followed by the command: * * * * * /path/to/command (minute, hour, day-of-month, month, day-of-week). Examples: 0 2 * * * /scripts/backup.sh (daily at 2 AM), */15 * * * * /scripts/check.sh (every 15 minutes), 0 9 * * 1 /scripts/weekly.sh (every Monday at 9 AM). System-wide crontabs live in /etc/cron.d/. Always use absolute paths in cron commands because the environment is minimal. Redirect output to avoid silent failures: command >> /var/log/cron.log 2>&1.

Open this question on its own page
04

How does systemd work with systemctl?

systemd is the init system and service manager used by most modern Linux distributions. systemctl is its command-line interface. Key commands: systemctl start nginx (start), systemctl stop nginx, systemctl restart nginx, systemctl reload nginx (reload config without full restart), systemctl status nginx (detailed status and recent logs), systemctl enable nginx (start on boot), systemctl disable nginx, systemctl is-active nginx (check status in scripts). View logs for a service with journalctl -u nginx -f (follow live) or journalctl -u nginx --since "1 hour ago". Service unit files live in /etc/systemd/system/ — after editing, run systemctl daemon-reload.

Open this question on its own page
05

How do you write if/for/while/case statements in bash?

Bash control structures: if: if [ "$var" = "value" ]; then echo yes; elif ...; else echo no; fi. Use [[ ]] (double brackets) for more features like =~ regex matching. for: for i in 1 2 3; do echo $i; done or C-style: for ((i=0; i<10; i++)); do ...; done. while: while read line; do ...; done < file reads a file line by line. case: case "$arg" in start) start_service;; stop) stop_service;; *) echo "unknown";; esac. Key test operators: -f (file exists), -d (directory), -z (string empty), -n (string not empty), -eq/-ne/-lt/-gt for numeric comparisons.

Open this question on its own page
06

How do bash functions work?

Bash functions group reusable commands: function greet() { echo "Hello, $1"; } or equivalently greet() { echo "Hello, $1"; }. Call with greet Alice. Inside a function, $1, $2, etc. refer to the function's arguments (not the script's). local var=value declares a variable local to the function, preventing it from leaking into the global scope — always use local for function variables. Functions return exit codes (0–255) via return N; use echo and command substitution to return string values: result=$(my_func). Functions must be defined before they are called in the script. Source a functions library into multiple scripts with source functions.sh.

Open this question on its own page
07

What is $? and how does exit status error handling work in bash?

$? holds the exit status of the last executed command — 0 means success, any non-zero value (1–255) indicates an error. Check it immediately after a command: cp src dst; if [ $? -ne 0 ]; then echo "copy failed"; exit 1; fi. Short-circuit operators provide concise handling: command || exit 1 (exit on failure), command && next_command (run next only if first succeeds). Set set -e at the top of a script to exit automatically on any unhandled error. Use exit N to terminate a script with a specific code. CI/CD systems check the script's exit code to determine pass/fail.

Open this question on its own page
08

How does trap work for signal handling in bash?

trap registers a command or function to be executed when the shell receives a specified signal or exits. Common patterns: trap "cleanup; exit" INT TERM runs cleanup when the script is interrupted (Ctrl+C) or terminated. trap cleanup EXIT runs cleanup on any exit — normal, error, or signal — making it the bash equivalent of a finally block. This is essential for scripts that create temporary files or acquire locks: TMPFILE=$(mktemp); trap "rm -f $TMPFILE" EXIT ensures the temp file is deleted no matter how the script ends. trap "" SIGINT ignores a signal. List current traps with trap -l.

Open this question on its own page
09

How do arrays work in bash?

Bash supports indexed arrays and associative arrays (bash 4+). Declare an indexed array: arr=("apple" "banana" "cherry") or arr[0]="apple". Access elements: ${arr[0]}. Get all elements: ${arr[@]}. Get length: ${#arr[@]}. Iterate: for item in "${arr[@]}"; do echo "$item"; done. Append: arr+=("date"). Associative arrays (declare first): declare -A map; map["key"]="value"; echo "${map["key"]}". Always quote array expansions with "${arr[@]}" to preserve elements with spaces. Arrays in bash are essential for collecting command output: files=($(find . -name "*.log")) — though mapfile/readarray is safer for filenames with spaces.

Open this question on its own page
10

How does xargs work for building command lines?

xargs reads items from stdin (typically newline or null-separated) and builds and executes command lines from them. Basic usage: find . -name "*.tmp" | xargs rm deletes all .tmp files found. xargs -n 2 passes at most 2 arguments per command invocation. xargs -P 4 runs up to 4 processes in parallel — great for speeding up operations on many files. xargs -I{} cmd {} extra uses a placeholder for precise argument placement: find . -name "*.jpg" | xargs -I{} convert {} {}.png. Always use -print0 with find and -0 with xargs to correctly handle filenames containing spaces or special characters: find . -name "*.log" -print0 | xargs -0 rm.

Open this question on its own page
11

What does lsof do and when is it useful?

lsof (list open files) shows all files currently opened by processes — and in Linux, "everything is a file" (network sockets, pipes, devices). Key uses: lsof -i :8080 shows what process is listening on port 8080 (useful when you get "address already in use"). lsof -p PID lists all files opened by a specific process. lsof -u alice shows all files opened by a user. lsof /path/to/file shows which processes have a particular file open. lsof -i TCP -n -P lists all TCP connections without hostname resolution. lsof is invaluable for diagnosing port conflicts, finding which process is holding a file that can't be deleted, and investigating resource leaks.

Open this question on its own page
12

What are strace and ltrace used for?

strace traces system calls made by a process — every interaction with the kernel (file opens, network ops, memory allocation, signals). Usage: strace -p PID attaches to a running process, or strace ./myapp arg traces from launch. strace -e trace=file filters to only file-related syscalls. strace -o output.txt ./myapp saves trace to a file. It is the go-to tool for diagnosing mysterious failures: "permission denied" (check which file it tries to open), "connection refused" (see the connect() call), or hangs (see what it's blocked on). ltrace similarly traces library function calls (libc functions like malloc, printf, strcpy). Both tools add significant overhead and are only for debugging, never production.

Open this question on its own page
13

How do netstat and ss show network connections?

ss (socket statistics) is the modern replacement for the deprecated netstat. Common usage: ss -tlnp shows all TCP (t) listening (l) sockets with numeric ports (n) and the process name/PID (p). ss -an shows all connections. ss -s prints a summary of socket counts by state. netstat -tlnp does the same on older systems. For troubleshooting connectivity: ss -tn dst 192.168.1.1 shows connections to a specific IP. Check TIME_WAIT accumulation (can cause port exhaustion) with ss -t state time-wait | wc -l. Both tools are essential for verifying that your application is listening on the expected port and diagnosing connection issues.

Open this question on its own page
14

How do you use the ip command for network configuration?

The ip command is the modern replacement for ifconfig and route. Key subcommands: ip addr show (or ip a) lists all network interfaces and their IP addresses. ip addr add 192.168.1.100/24 dev eth0 adds an IP address to an interface. ip link set eth0 up/down brings an interface up or down. ip route show displays the routing table. ip route add default via 192.168.1.1 adds a default gateway. ip neigh show displays the ARP cache. ip -s link shows interface statistics (packets sent/received, errors). Changes made with ip are non-persistent — they are lost on reboot. For persistent configuration, edit network config files (/etc/netplan/ on Ubuntu, /etc/sysconfig/network-scripts/ on RHEL).

Open this question on its own page
15

What are the basics of iptables for packet filtering?

iptables is the Linux kernel-level firewall. It processes packets through chains (INPUT, OUTPUT, FORWARD) within tables (filter, nat, mangle). Rules are checked top-to-bottom; the first match wins. Key commands: iptables -L -n -v lists current rules. iptables -A INPUT -p tcp --dport 80 -j ACCEPT allows inbound TCP on port 80. iptables -A INPUT -j DROP drops everything else (add this last). iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT allows return traffic for existing connections. iptables-save > /etc/iptables/rules.v4 persists rules. On modern systems, nftables and ufw (Ubuntu) or firewalld (RHEL/CentOS) provide friendlier interfaces over the same kernel functionality.

Open this question on its own page
16

What are /proc and /sys virtual filesystems in Linux?

/proc is a virtual filesystem that exposes kernel and process information as files. /proc/PID/ contains information about a specific process (exe, cmdline, fd, status, maps). /proc/cpuinfo shows CPU details, /proc/meminfo shows memory statistics, /proc/net/tcp shows TCP connections. These are not real files — they are generated on-demand by the kernel. /sys (sysfs) exposes the kernel's device tree and allows runtime configuration of drivers and hardware. Modify kernel parameters via /proc/sys/ using echo 1 > /proc/sys/net/ipv4/ip_forward (enables IP forwarding) or the higher-level sysctl -w net.ipv4.ip_forward=1. Both filesystems are essential for monitoring, debugging, and tuning a Linux system.

Open this question on its own page
17

What is the difference between a symbolic link and a hard link?

A hard link is a directory entry that points directly to the same inode (the file's data on disk) as the original file. Both the original and the hard link are equal — there is no "original." Deleting one does not affect the other; the data is removed only when all hard links to the inode are deleted. Hard links cannot cross filesystem boundaries and cannot link to directories. A symbolic (soft) link is a separate file that contains a path pointing to the target. It can cross filesystems and link to directories. If the target is deleted, the symlink becomes dangling. Create with ln file hardlink and ln -s target symlink. Symlinks are far more commonly used (e.g., /usr/bin/python/usr/bin/python3.11).

Open this question on its own page
18

What does set -euo pipefail do in bash scripts?

set -euo pipefail is the recommended safety header for production bash scripts. -e (errexit) causes the script to exit immediately when any command exits with a non-zero status — preventing silent failures from cascading. -u (nounset) treats references to undefined variables as errors, catching typos in variable names before they cause data loss (rm -rf $DIOR/ vs rm -rf $DIR/). -o pipefail makes a pipeline fail if any command in it fails, not just the last one — without this, cmd1 | cmd2 succeeds even if cmd1 fails because only cmd2's exit code is checked. Add set -euo pipefail as the second line of every non-trivial bash script.

Open this question on its own page
19

What is a heredoc (<<EOF) in bash and when is it used?

A heredoc is a multi-line string literal in bash that feeds input to a command until a delimiter line is reached. Syntax: command <<EOF\nline 1\nline 2\nEOF. Variables and command substitutions are expanded inside the heredoc by default. To suppress expansion (treat the content as a literal string), quote the delimiter: <<'EOF'. Use <<-EOF (with a dash) to allow indented delimiter tabs (but not spaces). Common uses: writing multi-line config files in scripts (cat > /etc/nginx/site.conf <<EOF), passing multi-line SQL to mysql, multi-line SSH commands, and embedding JSON payloads in curl calls. Heredocs make scripts far more readable than many escaped echo statements.

Open this question on its own page
20

What is process substitution in bash?

Process substitution treats the output of a command as if it were a file, using the syntax <(command) (for reading) or >(command) (for writing). This is useful when a command requires a filename argument but you want to feed it the output of another command. Example: diff <(sort file1) <(sort file2) compares the sorted versions of two files without creating temp files. while read line; do ...; done < <(find . -name "*.log") iterates over find results in the current shell (important: a plain pipe would run the while loop in a subshell, losing variable changes). Process substitution is a bash/zsh feature not available in POSIX sh.

Open this question on its own page
Advanced 10 questions

Deep expertise questions for senior and lead roles.

01

What are Linux namespaces and cgroups, and how do they underpin containers?

Namespaces provide isolation of system resources. Linux has seven namespace types: pid (isolates process IDs — a container sees its own PID 1), net (isolates network interfaces, routing, ports), mnt (isolates filesystem mount points), uts (isolates hostname and domain name), ipc (isolates inter-process communication), user (maps container UIDs to host UIDs), and cgroup (isolates cgroup root). Control groups (cgroups) enforce resource limits: CPU, memory, disk I/O, and network bandwidth. A Docker container is essentially a process (or group of processes) with all seven namespaces applied plus cgroup limits, given a root filesystem image. Understanding namespaces and cgroups explains what containers actually are at the kernel level — not VMs, but isolated process trees.

Open this question on its own page
02

How do iptables and nftables handle packet filtering rules?

iptables organizes rules into tables (filter, nat, mangle, raw) and chains (INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING). Packets traverse chains top-to-bottom; the first matching rule's target (ACCEPT, DROP, REJECT, LOG, MASQUERADE) is applied. Rule ordering is critical — more specific rules must come before general ones. iptables -I INPUT 1 ... inserts at position 1 (top). The stateful matching module (-m conntrack --ctstate) replaces the older -m state module. nftables (introduced in kernel 3.13, default on modern distros) replaces all four iptables tools with one unified framework, using a cleaner grammar, atomic rule updates (no mid-update inconsistency), and better performance via a virtual machine in the kernel. Migrate with iptables-translate. Both ultimately configure netfilter hooks in the kernel.

Open this question on its own page
03

What is LVM (Logical Volume Manager) and what problems does it solve?

LVM adds a layer of abstraction between physical disks and filesystems, enabling flexible volume management. The hierarchy: Physical Volumes (PV) — raw disks or partitions (pvcreate /dev/sdb). Volume Groups (VG) — a pool combining one or more PVs (vgcreate myvg /dev/sdb /dev/sdc). Logical Volumes (LV) — virtual partitions carved from a VG (lvcreate -L 50G -n data myvg), formatted and mounted like regular partitions. Key advantages: online resize (lvextend -L +20G /dev/myvg/data && resize2fs /dev/myvg/data — no unmounting needed), snapshots for consistent backups (lvcreate -L 10G -s -n snap /dev/myvg/data), and easy addition of new disks to an existing VG. LVM is essential for production servers where disk requirements change over time.

Open this question on its own page
04

How does /etc/fstab work and what are important mount options?

/etc/fstab defines filesystems to be mounted automatically at boot. Each line has six fields: device mountpoint fstype options dump pass. The device can be a path (/dev/sda1) or UUID (UUID=abc123) — always prefer UUIDs as they are stable across reboots and disk reorders. Important mount options: defaults (rw, suid, dev, exec, auto, nouser, async), noexec (prevents executing binaries — use on /tmp for security), nosuid (ignores setuid bits), noatime (disables access time updates — significant performance improvement for databases and high-traffic filesystems), ro (read-only), _netdev (wait for network before mounting — for NFS). Test fstab changes with mount -a before rebooting. The pass field (0/1/2) controls fsck order on boot.

Open this question on its own page
05

How do sysctl kernel parameters work and what are important tuning examples?

sysctl reads and writes kernel parameters exposed in /proc/sys/. View all: sysctl -a. Set temporarily: sysctl -w net.ipv4.ip_forward=1. Make permanent: add to /etc/sysctl.conf or a file in /etc/sysctl.d/, then apply with sysctl -p. Critical tuning examples for high-performance servers: net.core.somaxconn=65535 (maximum listen queue depth for TCP servers), net.ipv4.tcp_tw_reuse=1 (reuse TIME_WAIT sockets — reduces port exhaustion), net.ipv4.tcp_fin_timeout=15 (reduce FIN_WAIT2 timeout), vm.swappiness=10 (reduce swapping to prefer RAM), vm.overcommit_memory=1 (used by Redis to allow fork without OOM). Always test sysctl changes in staging — incorrect values can cause kernel panics or network outages.

Open this question on its own page
06

How do you use perf and flame graphs for performance analysis on Linux?

perf is Linux's built-in performance analysis tool backed by hardware performance counters. perf stat ./myapp records CPU metrics (instructions, cache misses, context switches) for one run. perf record -g ./myapp samples the call graph at 100Hz; perf report shows an interactive annotated hot-path breakdown. For a flame graph (a hierarchical visualization of where CPU time is spent): run perf record -g -p PID, then perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg using Brendan Gregg's tools. The width of each bar represents the proportion of time spent — wide bars at the top of the call stack are the hottest functions to optimize. Flame graphs are the industry standard for CPU profiling on Linux production systems.

Open this question on its own page
07

Describe the Linux boot process from BIOS to init.

The boot sequence: 1. BIOS/UEFI — firmware runs POST (power-on self test), detects hardware, and loads the bootloader from the boot device. 2. GRUB2 — the bootloader presents a menu (or boots immediately), loads the kernel image (vmlinuz) and the initial RAM disk (initrd/initramfs) into memory. 3. Kernel initialization — the kernel decompresses itself, initializes hardware subsystems (memory, interrupts, I/O), mounts the initramfs as a temporary root filesystem, and runs the early userspace tools to locate and mount the real root filesystem. 4. Real root filesystem mounted — the kernel pivots to the real root and executes /sbin/init (PID 1). 5. systemd (init) — PID 1 reads unit files, resolves dependencies, and starts all enabled services in parallel according to the target (e.g., multi-user.target or graphical.target). Understanding this sequence is essential for diagnosing boot failures and configuring custom boot parameters.

Open this question on its own page
08

How does file descriptor management work in Linux (0/1/2, /dev/null, redirection internals)?

Every process inherits three open file descriptors (FDs) by convention: FD 0 (stdin), FD 1 (stdout), FD 2 (stderr). All I/O in Linux is file I/O — network sockets, pipes, and devices are all FDs. Redirection works by duplicating and replacing FDs: 2>&1 duplicates FD 1 into FD 2 (stderr now goes where stdout goes). > file opens the file and assigns FD 1 to it. /dev/null is a character device that discards all writes and returns EOF on reads — command > /dev/null 2>&1 silences both streams. Order matters: 2>&1 > file is wrong (redirects stderr to the current stdout, then redirects stdout to file, leaving stderr pointing to original stdout). FD limits per process are set by ulimit -n (view with ulimit -n, typically 1024 or 65536 on production servers — insufficient limits are a common cause of "too many open files" errors).

Open this question on its own page
09

What are the key differences between POSIX sh and bash?

POSIX sh is the standardized shell specification — portable across all UNIX/Linux systems. Scripts starting with #!/bin/sh should use only POSIX features for maximum portability. Key bash-only features not in POSIX sh: double brackets ([[ ]]) with =~ regex, arrays (arr=()), associative arrays (declare -A), process substitution (<(cmd)), local variables in functions (technically not in POSIX), heredoc variations, {a..z} brace expansion, ANSI-C quoting with $'\\n', mapfile/readarray, and PIPESTATUS. On some systems (Alpine Linux, embedded systems) /bin/sh is dash (a minimal POSIX shell), so bash-isms in #!/bin/sh scripts will fail. Use #!/bin/bash explicitly when using bash features and run shellcheck to catch portability issues.

Open this question on its own page
10

How do you write robust production shell scripts with locking and atomic writes?

Production-grade scripts require several patterns. Exclusive locking with flock prevents multiple instances running simultaneously: exec 9>/var/lock/myscript.lock; flock -n 9 || { echo "Already running"; exit 1; } — the lock is automatically released when the script exits. Atomic writes prevent readers from seeing partially-written files: write to a temp file on the same filesystem then rename: TMP=$(mktemp /target/dir/.tmp.XXXXXX); write_data > "$TMP" && mv "$TMP" /target/filemv within a filesystem is atomic at the kernel level. Additional robustness patterns: use set -euo pipefail, validate all inputs before use, use trap for cleanup, log with timestamps to a dedicated log file, never use ls output in scripts (use globs or find instead), quote all variable expansions, and use shellcheck in CI to catch common errors automatically.

Open this question on its own page
Back to All Topics 50 questions total