Skip to content

Linux_Practical_Interview_1 100

Linux Practical Interview Questions (1-100)

Section titled “Linux Practical Interview Questions (1-100)”

Q1: How do Linux kernel and user space interact?

Section titled “Q1: How do Linux kernel and user space interact?”

What it is: The kernel and user space communicate through system calls; an application calls libc, which wraps the call into the kernel. strace shows these calls and man syscalls lists them.

Why it is used: To see exactly which kernel services an application requests when it misbehaves or fails.

Terminal window
# System call interface
# User space -> libc -> system call wrapper -> kernel
# Example: read() system call
ssize_t read(int fd, void *buf, size_t count);
# View system calls
strace -e trace=read,write cat /etc/passwd
# List system calls
man syscalls
# or
cat /usr/include/asm/unistd_64.h | head -30

Interview talking point: “strace -e trace=read,write narrows the output to specific syscalls, which keeps a trace readable when debugging a noisy program. The unistd header shows read and write are just numbered entries, not magic.”

What it is: cat /proc/cpuinfo lists per-processor details, lscpu prints a summarized view of CPU architecture, and top shows live CPU consumption by process.

Why it is used: To check core counts and identify processes eating CPU time.

Terminal window
# CPU info
cat /proc/cpuinfo
# or
lscpu
# or
top

Interview talking point: “lscpu is the one-shot summarized answer for cores and architecture, /proc/cpuinfo gives per-processor detail, and top adds the real-time usage view on top of that.”


What it is: uptime reports how long the system has been running plus load averages, uptime -p prints a readable duration, and /proc/uptime holds the raw seconds.

Why it is used: A fast first check after a reboot or when investigating load complaints.

Terminal window
# Check uptime
uptime
# or
uptime -p # pretty format
# or
cat /proc/uptime

Interview talking point: “uptime -p gives an easy to read “up 3 days” style line, and the trailing three numbers are load averages over 1, 5, and 15 minutes, not CPU percentages.”

Q4: How do you check the current kernel version?

Section titled “Q4: How do you check the current kernel version?”

What it is: uname -r prints the running kernel release, cat /proc/version prints the fuller kernel version string, and hostnamectl shows kernel info alongside host details.

Why it is used: To confirm which kernel is live before installing modules, applying patches, or rebooting.

Terminal window
# Check kernel version
uname -r
# or
cat /proc/version
# or
hostnamectl

Interview talking point: “uname -r is the quick answer giving just the release string, while cat /proc/version adds build detail such as the compiler, and hostnamectl bundles kernel info with hostname and init details.”

What it is: mkfifo creates a named pipe, a special file where data written in one terminal is read in another. It also shows process substitution feeding sorted files into diff and a while-read loop.

Why it is used: It lets two shell sessions exchange data through the filesystem, and pipe command output where a plain pipeline will not do.

Terminal window
# Create named pipe
mkfifo /tmp/myfifo
# In one terminal (read)
cat < /tmp/myfifo
# In another terminal (write)
echo "Hello" > /tmp/myfifo
# Process substitution
diff <(sort file1) <(sort file2)
# While reading
while read line; do echo "$line"; done < /tmp/myfifo

Interview talking point: “A FIFO blocks until both a reader and a writer appear, so cat waits at the shell until echo writes; process substitution gives temporary file-like inputs without creating any file in the directory.”

What it is: SUID (4) makes a file run as its owner, SGID (2) runs it as its group, and the sticky bit (1) limits deletion in shared directories such as /tmp.

Why it is used: To grant limited privilege for specific tools and protect files in world-writable directories.

Terminal window
# SUID (set user ID)
chmod 4755 file # or chmod u+s file
# SGID (set group ID)
chmod 2755 directory # or chmod g+s directory
# Sticky bit
chmod 1777 /tmp # or chmod +t /tmp
# View
ls -l file # shows s or t

Interview talking point: “the special digits 4, 2, and 1 prepend to the normal mode, so 1777 on /tmp is sticky plus full permissions, and ls -l reveals them as s and t characters.”

What it is: chmod changes permission bits either numerically like 755 or symbolically like +x, chown changes the owner and group, and ls -l displays the result.

Why it is used: To lock down scripts, grant execute rights, or fix ownership after a restore.

Terminal window
# Change permissions
chmod 755 file
chmod +x script.sh
chmod -R 644 directory/
# Change owner
chown user:group file
# View permissions
ls -l file

Interview talking point: “chmod 755 gives the owner full access and others read and execute, while chmod +x only adds execute, and ls -l is where you verify both the owner and the mode.”

What it is: df -h reports usage per mounted filesystem, du -sh totals a directory subtree, and lsblk lists block devices and their partitions.

Why it is used: To find which mount is full and which folders are consuming the space.

Terminal window
# Disk usage
df -h
# or
du -sh /path/to/directory
# or
lsblk

Interview talking point: “df answers which filesystem is full, du -sh answers which directory grew, and lsblk shows the actual devices sitting behind those mount points.”

What it is: find walks a directory tree and matches files by name, type, size, or modification time using tests such as -name, -type, -size, and -mtime.

Why it is used: To locate files anywhere on a filesystem by criteria rather than by memory of the path.

Terminal window
# Find files
find /path -name "filename"
# Find by type
find /path -type f -name "*.log"
# Find by size
find /path -size +100M
# Find by modified time
find /path -mtime -7

Interview talking point: “the tests stack in one invocation, and -mtime -7 means modified within the last seven days, which is the usual way to find recently changed files.”

What it is: grep searches file contents for a pattern; -r recurses into directories, -i ignores case, -n prints line numbers, and -E enables extended regular expressions.

Why it is used: To trace errors, keys, or config values across log directories and files.

Terminal window
# Search in files
grep -r "search_term" /path
# Case insensitive
grep -ri "search_term" /path
# Show line numbers
grep -n "search_term" file
# Use regex
grep -E "pattern" file

Interview talking point: “-i and -n are the everyday switches for case-insensitive hits with line numbers, while -E changes the regex flavor, since plain grep uses basic regular expressions.”

Q11: How do you compress and decompress files?

Section titled “Q11: How do you compress and decompress files?”

What it is: gzip compresses a single file, tar archives whole directories with optional gzip compression via -z, and zip builds an archive that unzip extracts.

Why it is used: To shrink logs or bundle a directory tree for transfer, backup, or shipping.

Terminal window
# gzip compression
gzip file
gunzip file.gz
# tar archive
tar -cvf archive.tar directory/
tar -xvf archive.tar
tar -czvf archive.tar.gz directory/
tar -xzvf archive.tar.gz
# zip
zip -r archive.zip directory/
unzip archive.zip

Interview talking point: “tar -czvf creates a gzipped tarball and -xzvf unpacks it, while the v flag prints each member file as it is processed, and c means create while x means extract.”


What it is: tar archives files into a single file, optionally compressed with gzip or bzip2. It can create, extract, and list archives, and take a snapshot file to support incremental backups.

Why it is used: To bundle directories into one compressed file for backup, archiving, or moving between systems.

Terminal window
# Create archive
tar -cvf backup.tar /data
tar -cvzf backup.tar.gz /data
tar -cvjf backup.tar.bz2 /data
# Extract
tar -xvf backup.tar
tar -xvzf backup.tar.gz
# List contents
tar -tvf backup.tar
# Incremental backup
tar -g /var/log/backup.snap -cvzf backup-incremental.tar.gz /data
# With date
tar -cvzf backup-$(date +%Y%m%d).tar.gz /data

Interview talking point: “The compression letter changes with the archiver used: z pairs with gzip and j with bzip2 on create and extract alike, and the snapshot file makes later runs pick up only changed files.”

What it is: tar creates, extracts, and lists archive files. c, x, and t select create, extract, and list; v prints file names, f names the archive, and z, j, and J add gzip, bzip2, or xz compression.

Why it is used: To bundle many files into one archive for storage or transfer.

Terminal window
# Create archive
tar -cvf archive.tar file1 file2 directory/
# With compression
tar -czvf archive.tar.gz directory/
tar -cjvf archive.tar.bz2 directory/
tar -cJvf archive.tar.xz directory/
# Extract
tar -xvf archive.tar
tar -xzvf archive.tar.gz
tar -xjvf archive.tar.bz2
# List
tar -tvf archive.tar

Interview talking point: “The letters form a recipe: czvf builds a gzipped archive, xzvf unpacks one, and tvf only lists contents, so the compression letter has to match the archive’s file extension.”

What it is: useradd creates an account, optionally with a home directory via -m, passwd sets the password, usermod -aG adds a user to a group, and userdel removes the account.

Why it is used: To provision access for new team members and revoke it when they leave.

Terminal window
# Create user
useradd username
# or with home directory
useradd -m username
# Set password
passwd username
# Add to group
usermod -aG groupname username
# Delete user
userdel username
# Check user info
id username

Interview talking point: “the -a in usermod -aG appends to supplementary groups instead of overwriting them, and id username is how you verify the resulting uid, gid, and group memberships.”

What it is: who and w list current login sessions, last and lastlog review past logins, and whoami prints the effective user you are acting as.

Why it is used: To audit who is on a machine and review login history.

Terminal window
# Who is logged in
who
w
# Last login
last
lastlog
# Current user
whoami

Interview talking point: “who shows who is logged in right now while last reads historical login records, and w goes a step further by showing what each session is currently doing.”


What it is: Editing /etc/sudoers through visudo to grant rules such as full privileges, NOPASSWD passwordless access, a restricted list of commands, or a rule applying to the whole sudo group.

Why it is used: Giving administrators controlled privilege elevation without sharing the root password, in an auditable rule set.

Terminal window
# Edit sudoers
visudo
# Grant all privileges
username ALL=(ALL:ALL) ALL
# Passwordless
username ALL=(ALL) NOPASSWD: ALL
# Specific commands
username ALL=(ALL) /bin/ls, /bin/kill
# Group
%sudo ALL=(ALL:ALL) ALL

Interview talking point: “visudo checks syntax before saving and refuses a broken file, which matters because a syntax error in sudoers can lock every administrator out of sudo.”

What it is: visudo safely edits the sudoers file, where a rule grants a user sudo on all hosts and the NOPASSWD variant skips the password prompt.

Why it is used: To delegate administrative commands without sharing the root password.

Terminal window
# Edit sudoers file
visudo
# Grant sudo access
username ALL=(ALL:ALL) ALL
# Passwordless sudo
username ALL=(ALL) NOPASSWD: ALL

Interview talking point: “visudo checks syntax before saving, which guards against a typo that would break sudo for everyone, and it is the only sanctioned way to edit sudoers for that reason.”

What it is: usermod -L or passwd -l disables login by locking the password, usermod -U or passwd -u reverses the lock, and passwd -S reports the current account status.

Why it is used: Suspending an account during leave or incident response without deleting it or losing home directory data.

Terminal window
# Lock account
usermod -L username
# or
passwd -l username
# Unlock
usermod -U username
# or
passwd -u username
# Check status
passwd -S username

Interview talking point: “The lock only affects the password, so already running sessions keep going and SSH keys may still authenticate until you take further action on the account.”

What it is: Password aging rules set globally in /etc/login.defs such as PASS_MAX_DAYS 90 and PASS_MIN_LEN 12, or per user with chage flags like -M, -m, -W, and inspected with chage -l.

Why it is used: Enforcing expiry, minimum age, and warning windows so stale credentials rotate on a schedule.

/etc/login.defs
# PAM configuration
PASS_MAX_DAYS 90
PASS_MIN_DAYS 1
PASS_MIN_LEN 12
PASS_WARN_AGE 7
# Or using chage
# Set password expiration
chage -M 90 username
chage -m 1 username
chage -W 7 username
# View
chage -l username

Interview talking point: “login.defs supplies defaults for accounts created afterward, while chage -M 90 username overrides one existing account immediately, and chage -l shows the effective dates that result.”

What it is: Creating groups with groupadd in a loop, then assigning membership either in one shot with gpasswd -M user list or one user at a time with usermod -aG.

Why it is used: Granting team-wide access to shared resources quickly when many users need the same group permissions.

Terminal window
# Create groups
for group in group1 group2 group3; do
groupadd "$group"
done
# Add users to group
gpasswd -M user1,user2,user3 groupname
# Add users one by one
for user in user1 user2; do
usermod -aG groupname "$user"
done

Interview talking point: “gpasswd -M replaces the whole member list in one call, while usermod -aG appends and needs the -a flag to avoid overwriting any supplementary groups the user already had.”

What it is: Reading a colon-delimited file line by line and calling useradd with uid, gid, home, shell, and comment fields for each entry, then setting passwords in bulk by piping user:password pairs into chpasswd.

Why it is used: Onboarding dozens of accounts at once without typing each useradd interactively, keeping IDs and shells consistent across a fleet.

Terminal window
# Create users from file
while IFS=: read -r user pass uid gid info home shell; do
useradd -u "$uid" -g "$gid" -d "$home" -s "$shell" -c "$info" "$user"
done < users.txt
# Password in bulk
for user in user1 user2 user3; do
echo "$user:password" | chpasswd
done
# CSV import
# username,uid,gid,info,home,shell,password

Interview talking point: “chpasswd accepts user:password lines on standard input, so it fits loops and scripts, unlike passwd which prompts per user; the users.txt row order must match the field order the read loop expects.”

Q22: How do you check process resource usage?

Section titled “Q22: How do you check process resource usage?”

What it is: top and htop show live CPU and memory per process, ps aux sorted by %cpu or %mem ranks them, and /proc/PID/status holds detailed counters for one process.

Why it is used: To identify which process is consuming CPU or memory.

Terminal window
# CPU and memory
top
htop
# Per-process
ps aux --sort=-%cpu | head
ps aux --sort=-%mem | head
# Detailed
/proc/PID/status

Interview talking point: “ps aux —sort=-%cpu | head gives a sorted snapshot you can paste straight into a ticket, while top keeps refreshing live as the situation changes.”

What it is: ps takes a snapshot of processes with aux and -ef being the common full listings, top and htop are interactive views, and pstree shows parent-child relationships.

Why it is used: To inventory running services and grab the PID of a process you need to act on.

Terminal window
# View processes
ps
ps aux
ps -ef
# Interactive
top
htop
# Tree view
pstree

Interview talking point: “ps aux is the BSD style and ps -ef is the System V style, and they show the same processes with slightly different column headers, so either is acceptable in an interview.”

What it is: htop is an interactive process viewer. It can be filtered to a user with -u or to specific PIDs with -p, and function keys handle search, filter, tree view, sorting, and killing.

Why it is used: To inspect and manage running processes with a keyboard-driven interface clearer than top.

Terminal window
# Install
apt install htop
# Run
htop
# Options
htop -u user
htop -p PID1,PID2
# Interactive
# F3: search
# F4: filter
# F5: tree
# F6: sort
# F9: kill

Interview talking point: “htop -u user and htop -p PID1,PID2 narrow the display at startup instead of filtering by hand, and F5 tree view shows parent-child relationships, which is how you spot a process spawned by a supervisor. F9 kills the selected process directly.”

What it is: kill sends a signal to a PID: 15 is SIGTERM for graceful shutdown, 9 is SIGKILL to force it, 2 is SIGINT like Ctrl+C; pkill and killall target by name.

Why it is used: To stop hung, runaway, or unwanted processes quickly.

Terminal window
# Kill by PID
kill -15 pid # SIGTERM (graceful)
kill -9 pid # SIGKILL (force)
kill -2 pid # SIGINT (Ctrl+C)
# Kill by name
pkill process_name
killall process_name
# Kill processes by pattern
pgrep pattern | xargs kill

Interview talking point: “SIGTERM lets the program clean up while SIGKILL cannot be caught or ignored, so try 15 before 9, and pgrep pattern piped through xargs kill achieves the same as pkill.”

What it is: an ampersand runs a command in the background, jobs lists them, fg and bg move them around, Ctrl+Z suspends a running job, and nohup keeps it alive after logout.

Why it is used: To keep long tasks running while staying productive in the same shell.

Terminal window
# Run in background
command &
# List jobs
jobs
# Bring to foreground
fg %1
# Send to background
Ctrl+Z
bg %1
# Run nohup
nohup command &

Interview talking point: “Ctrl+Z suspends the current job which you resume with bg %1, whereas nohup protects a job from the terminal closing, and simply backgrounding with an ampersand does not.”

What it is: A bash array stores multiple values under one name indexed from zero, with ${arr[@]} expanding all elements, ${#arr[@]} giving the length, and arr+= appending a new element.

Why it is used: To manage lists of hosts, files, or options without clumsy variable names.

Terminal window
# Define array
arr=(one two three)
arr[0]="one"
# Access elements
echo ${arr[0]}
echo ${arr[@]}
# Length
echo ${#arr[@]}
# Loop
for item in "${arr[@]}"; do
echo $item
done
# Add elements
arr+=("four")

Interview talking point: “quoting ”${arr[@]}” keeps elements containing spaces intact during iteration, and ${#arr[@]} reports the element count while ${arr[0]} addresses a single item by index.”

What it is: Bash parameter expansion gives string length with ${#string}, a slice with ${string:position:length}, substitution with ${string/pattern/replacement}, prefix trimming with # or ##, and case changes with ^^ and ,,.

Why it is used: To transform text inside a script without calling sed or awk.

Terminal window
# Length
${#string}
# Substring
${string:position}
${string:position:length}
# Replace
${string/pattern/replacement}
${string//pattern/replacement}
# Pattern removal
${string#pattern} # shortest match
${string##pattern} # longest match
# Case conversion
${string^^}
${string,,}

Interview talking point: “a single slash replaces the first match while a double slash replaces all matches, and a single # trims the shortest prefix match while a double ## trims the longest.”

What it is: Positional parameters hold arguments: $0 is the script name, $1 the first, $# the count, $@ all of them, $$ the PID, and getopts parses flags such as -h, -v, and -c with a value.

Why it is used: To turn a fixed script into a reusable command-line tool.

#!/bin/bash
# Arguments
echo $0 # Script name
echo $1 # First argument
echo $# # Number of arguments
echo $@ # All arguments
echo $$ # PID
# Loop through arguments
for arg in "$@"; do
echo $arg
done
# Getopts
while getopts "hvc:" opt; do
case $opt in
h) echo "Help";;
v) echo "Version";;
c) echo "Config: $OPTARG";;
esac
done

Interview talking point: ""$@” preserves each argument separately so the for loop handles values containing spaces, and getopts places the value attached to -c into $OPTARG for the matching case branch.”

What it is: CSV parsing with a read loop using comma as IFS, header skipping via tail, or awk with -F to split fields and map header names to indexes.

Why it is used: To pull columns out of tabular exports for reporting or automation.

Terminal window
# Basic parsing
while IFS=',' read -r col1 col2 col3; do
echo "$col1 $col2 $col3"
done < file.csv
# Skip header
tail -n +2 file.csv | while IFS=',' read -r col1 col2 col3; do
echo "$col1 $col2 $col3"
done
# Using awk
awk -F',' '{print $1,$2}' file.csv
# With headers
awk -F',' 'NR==1 {for(i=1;i<=NF;i++) h[$i]=i} NR>1 {print $h["name"],$h["age"]}' file.csv

Interview talking point: “awk maps header names to column numbers on the first row, so later rows can be printed by column name instead of a hard-coded position that breaks when the export changes.”

What it is: jq is a command line JSON processor that filters with paths, applies conditionals, and edits fields, reading from files or piped input.

Why it is used: To extract or transform values from API responses and config files inside shell scripts.

Terminal window
# Using jq
apt install jq
# Parse JSON
echo '{"name":"John","age":30}' | jq '.name'
echo '{"users":["Alice","Bob"]}' | jq '.users[0]'
# Conditional
echo '{"status":"ok"}' | jq 'if .status == "ok" then "success" else "failed" end'
# Modify
echo '{"name":"John"}' | jq '.age = 30'
# From file
jq '.users[]' data.json
# With variables
NAME=$(echo "$JSON" | jq -r '.name')

Interview talking point: “jq -r prints raw strings without quotes so the result can be assigned to a shell variable, while plain jq output keeps JSON quoting and structure.”

What it is: jq reads JSON on stdin and extracts fields with paths like .name, filters array elements with select, and builds or modifies JSON objects.

Why it is used: To query and reshape API responses or config files directly from the shell.

Terminal window
# Using jq
# Parse JSON
cat data.json | jq '.name'
cat data.json | jq '.items[].value'
# Filter
cat data.json | jq '.items[] | select(.id > 5)'
# Transform
cat data.json | jq '{name: .name, computed: .value * 2}'
# Arrays
cat data.json | jq '.items | length'
cat data.json | jq '.items | map(.name)'
# Create JSON
jq -n '{name: "test", items: [1,2,3]}'
# Modify
jq '.name = "new"' data.json
jq '.items += ["new"]' data.json
# Input from variable
data='{"name":"test"}'
echo "$data" | jq '.name'

Interview talking point: “jq -n generates JSON from nothing so you can construct documents, and the assignment forms let you update a field or append to an array without another tool.”

What it is: jq is the command-line JSON processor: it extracts fields and array elements, filters with select, builds JSON with -n, and rewrites values in place.

Why it is used: To inspect and transform JSON from APIs without writing a parser.

Terminal window
# Using jq
cat data.json | jq '.name'
cat data.json | jq '.items[].value'
cat data.json | jq '.items[] | select(.id > 5)'
# Create JSON
jq -n '{name: "test", items: [1,2,3]}'
# Modify
jq '.name = "new"' data.json
# Filter
jq '.items[] | select(.age > 25)' data.json

Interview talking point: “jq -n builds JSON from scratch with no input, while plain jq reads stdin, and select(.id > 5) filters array elements inside a pipeline.”

What it is: jq queries and reshapes JSON from the command line, selecting paths and array items, filtering with select, computing with map and length, and building new objects.

Why it is used: To pull fields out of API responses or config JSON inside shell pipelines.

Terminal window
# Using jq
cat data.json | jq '.name'
cat data.json | jq '.items[].id'
cat data.json | jq 'map(select(.age > 25))'
cat data.json | jq '.items | length'
# Create JSON
jq -n '{name: "test", value: 42}'
# Modify JSON
cat data.json | jq '.name = "new_name"'
cat data.json | jq '.items += [{"id": 3}]'
# Filter
cat data.json | jq '.items[] | select(.id == 2)'

Interview talking point: “jq ‘.items[].id’ walks an array while map(select(.age > 25)) filters objects, and -n lets jq create JSON with no input, so it works as a generator as well as a filter.”

Q35: How do you use awk for text processing?

Section titled “Q35: How do you use awk for text processing?”

What it is: awk processes text field by field, printing columns, taking a custom field separator, applying conditions, and summing values in an END block.

Why it is used: To extract and aggregate columns from logs, CSV files, and reports.

Terminal window
# Print columns
awk '{print $1}' file
# Field separator
awk -F',' '{print $2}' file
# Conditional
awk '$3 > 50 {print $1}' file
# Sum values
awk '{sum+=$1} END {print sum}' file

Interview talking point: “fields are $1, $2 and so on, split on whitespace until -F’,’ changes the separator for CSV, and the END block runs once after all input is consumed.”

Q36: How do you use awk for text processing?

Section titled “Q36: How do you use awk for text processing?”

What it is: awk splits each line into fields and applies rules per line, selecting fields by number, filtering with patterns, and totaling in an END block.

Why it is used: To extract, filter, and total columns from logs or config files quickly.

Terminal window
# Basic usage
awk '{print $1}' file.txt
awk -F: '{print $1, $6}' /etc/passwd
# Conditional
awk '$3 > 1000 {print $1, $3}' /etc/passwd
# Calculations
awk '{sum+=$1} END {print sum}' numbers.txt
# Multiple fields
awk '{print "User:" $1 " UID:" $3 " Home:" $6}' /etc/passwd
# Patterns
awk '/^root/ {print}' /etc/passwd
awk 'NR==5 {print}' file.txt
# Field separator
awk -F: '{print NF}' /etc/passwd

Interview talking point: “The -F flag sets the field separator, so -F: works on /etc/passwd and NF reports how many fields a line has, while NR==5 targets one specific line number.”

What it is: awk processes text field by field, printing columns, applying conditions, matching patterns, and accumulating totals in an END block.

Why it is used: To extract, filter, and total columns from logs and system files.

Terminal window
# Basic
awk '{print $1}' file.txt
# Field separator
awk -F: '{print $1, $6}' /etc/passwd
# Conditional
awk '$3 > 1000 {print $1, $3}' /etc/passwd
# Calculations
awk '{sum+=$1} END {print sum}' numbers.txt
# Patterns
awk '/ERROR/ {print}' logfile
# Multiple fields
awk '{for(i=1;i<=NF;i++) sum[i]+=$i} END {for(i in sum) print i, sum[i]}' file.txt

Interview talking point: “-F: sets the colon separator for /etc/passwd, $3 > 1000 is the condition, and NF counts fields, which the loop uses to sum every column.”

What it is: Process substitution wraps a command’s output as a file-like argument, letting diff or comm compare two command outputs directly. It can also feed multiple files to a loop or to grep.

Why it is used: To pass command output to tools that insist on filename arguments instead of standard input.

Terminal window
# Compare two command outputs
diff <(command1) <(command2)
# Read from multiple files
while read line; do echo "$line"; done < <(cat file1 file2)
# Feed output to command expecting file
grep pattern <(echo "line with pattern")
# Multiple inputs
comm <(sort file1) <(sort file2)

Interview talking point: “Unlike a pipe, process substitution exposes each command’s output as a named input, which is why diff takes two such arguments even though diff expects two files rather than stdin.”

What it is: Regex usage across grep -oE for extraction, the bash =~ test for validation, sed -E with capture groups for rewrites, and awk for field-level matching.

Why it is used: To extract, validate, and transform text patterns in logs and data files.

Terminal window
# Extract IP addresses
grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' file.txt
# Validate email
email="user@example.com"
if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "Valid"
fi
# Extract dates
grep -oE '[0-9]{4}-[0-9]{2}-[0-9]{2}' file.txt
# Replace with sed
sed -E 's/([0-9]{4})([0-9]{2})([0-9]{2})/\1-\2-\3/g' file.txt
# Using awk
awk '/pattern/ {print $1, $2}' file.txt
awk 'match($0, /[0-9]+/) {print substr($0, RSTART, RLENGTH)}' file.txt
# Complex parsing
awk '
BEGIN { FPAT = "([^,]+)|(\"[^\"]+\")" }
{
for (i=1; i<=NF; i++) {
gsub(/^"|"$/, "", $i)
print i ": " $i
}
}
' data.csv

Interview talking point: “The bash =~ test returns true on a match with no output, while sed needs the g flag to replace every occurrence on a line, not just the first.”

Q40: How do you use sed for text manipulation?

Section titled “Q40: How do you use sed for text manipulation?”

What it is: sed edits text streamwise with substitutions and line deletions, using g for every match on a line, a number for one occurrence, and -i for in-place writes.

Why it is used: To bulk-edit config files or strip lines without opening an editor.

Terminal window
# Replace text
sed 's/old/new/' file.txt
sed 's/old/new/g' file.txt
sed 's/old/new/2' file.txt
# In-place editing
sed -i 's/old/new/g' file.txt
# Delete lines
sed '/pattern/d' file.txt
sed '1,5d' file.txt
sed '5d' file.txt
# Insert text
sed '1i\Header line' file.txt
sed '1a\New line' file.txt
# Regex
sed -E 's/[0-9]+/[REDACTED]/g' file.txt

Interview talking point: “Without g, sed replaces only the first match per line, and sed -i writes the file directly, so a mistake is permanent. -E enables extended regex for patterns such as digits replaced with REDACTED.”

Q41: How do you use sed for text processing?

Section titled “Q41: How do you use sed for text processing?”

What it is: sed is a stream editor that substitutes text, edits a file in place with -i, deletes lines matching a pattern, and with -n prints only chosen lines.

Why it is used: To batch-edit configuration files or transform output inside pipelines.

Terminal window
# Replace text
sed 's/old/new/g' file
# In-place edit
sed -i 's/old/new/g' file
# Delete lines
sed '/pattern/d' file
# Print specific line
sed -n '5p' file

Interview talking point: “without -i sed only writes to stdout so the file on disk is untouched, and sed -n ‘5p’ suppresses the default printing so just line five comes out.”

What it is: sed edits text streams with substitutions, line deletions, insertions, and extended regex, optionally writing results back into the file.

Why it is used: To repeat the same text change across files without opening an editor.

Terminal window
# Replace
sed 's/old/new/' file.txt
sed 's/old/new/g' file.txt
sed -i 's/old/new/g' file.txt
# Delete lines
sed '/pattern/d' file.txt
sed '1,5d' file.txt
# Insert
sed '1i\Header' file.txt
# Regex
sed -E 's/[0-9]{4}/[REDACTED]/g' file.txt
# In-place with backup
sed -i.bak 's/old/new/g' file.txt

Interview talking point: “Without g sed replaces only the first match per line, -i edits the file in place while -i.bak leaves a backup beside it, and -E enables extended regex.”

What it is: xargs reads items from standard input and appends them as arguments to another command. The examples show it replacing find -exec, running jobs in parallel, using a custom delimiter, and prompting before acting.

Why it is used: It turns a stream of filenames or tokens into real command arguments without shell loops.

Terminal window
# Find and delete
find /tmp -type f -name "*.tmp" -exec rm {} \;
# Equivalent using xargs
find /tmp -type f -name "*.tmp" | xargs rm
# Parallel processing
ls *.jpg | xargs -n 1 -P 4 convert -resize 800x600
# With custom delimiter
echo "a:b:c" | xargs -d ':' -n1
# Prompt before execution
ls | xargs -p rm

Interview talking point: “The find -exec and xargs versions look equivalent, but xargs adds -n 1 -P 4 to run four conversions at once, -d to split on a custom separator, and -p to confirm each run.”

Q44: How do you write a basic shell script?

Section titled “Q44: How do you write a basic shell script?”

What it is: A bash script starts with a shebang, sets variables, reads input with read -p, branches with if, repeats with for, and groups reusable logic in a function.

Why it is used: To automate repetitive administrative tasks consistently.

#!/bin/bash
# Comments
# Variables
NAME="John"
echo "Hello $NAME"
# User input
read -p "Enter name: " NAME
# Conditionals
if [ "$NAME" == "John" ]; then
echo "Hello John"
fi
# Loops
for i in {1..5}; do
echo $i
done
# Functions
function greet() {
echo "Hello $1"
}
greet "World"

Interview talking point: “quoting “$NAME” in the test protects against empty or space-containing values, and the shebang on line one is what tells the kernel which interpreter runs the script.”

Q45: How do you write efficient bash scripts?

Section titled “Q45: How do you write efficient bash scripts?”

What it is: Robust bash scripts start with a shebang, enable set -euo pipefail, wrap repeated work in functions, parse flags with getopts, and trap errors.

Why it is used: To make automation fail loudly and predictably instead of silently continuing after an error.

#!/bin/bash
set -euo pipefail
# Use functions
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*"
}
# Parse arguments
while getopts "hvf:" opt; do
case $opt in
h) help; exit 0 ;;
v) VERBOSE=1 ;;
f) FILE="$OPTARG" ;;
*) exit 1 ;;
esac
done
# Use arrays
files=("file1" "file2" "file3")
for file in "${files[@]}"; do
process "$file"
done
# Error handling
trap 'echo "Error on line $LINENO"' ERR

Interview talking point: “set -e exits on error, set -u treats unset variables as errors, and pipefail makes a pipeline fail if any stage fails, so the trio catches mistakes early. trap then reports the failing line number.”

Q46: How do you write efficient bash scripts?

Section titled “Q46: How do you write efficient bash scripts?”

What it is: The script shows bash reliability and speed habits: strict mode, a restricted IFS, helper functions, arrays, read loops, and parallel -j 4 for batches.

Why it is used: To make automation fail fast, handle data safely, and finish sooner.

#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
# Use functions
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*"
}
# Use arrays
files=("file1" "file2" "file3")
for file in "${files[@]}"; do
[[ -f "$file" ]] || continue
process "$file"
done
# Process efficiently
while IFS= read -r line; do
((count++))
done < <(grep -r "pattern" .)
# Parallel processing
parallel -j 4 process {} ::: *.log

Interview talking point: “set -euo pipefail makes the script exit on errors, unset variables, or a failed pipeline stage, while arrays and quoted loops keep filenames with spaces intact.”

What it is: Efficient bash uses set -euo pipefail, arrays for loops, local variables in functions, process substitution, coprocesses, and parallel for concurrent work.

Why it is used: To make scripts faster, safer, and free of common word-splitting and error-handling bugs.

#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
# Use arrays for loops
files=( /var/log/*.log )
for file in "${files[@]}"; do
[[ -f "$file" ]] || continue
process "$file"
done
# Use functions with local variables
process() {
local file="$1"
local content
content=$(<"$file")
echo "${content:0:100}"
}
# Avoid subshells in loops
while IFS= read -r line; do
((count++))
done < <(grep -r "pattern" .)
# Use coprocesses
coproc BC { bc -l; }
echo "scale=10; 355/113" >&${BC[1]}
read -r pi <&${BC[0]}
# Use process substitution
diff <(sort file1) <(sort file2)
# Parallel processing
parallel -j 4 process {} ::: *.log

Interview talking point: “Reading a loop from process substitution instead of a pipe keeps the loop in the current shell, so counters like count persist rather than vanishing inside a subshell.”

What it is: Script error handling combining set -euo pipefail, a trap-based cleanup handler on EXIT, input validation functions, and a bounded retry helper.

Why it is used: To fail fast with clear messages instead of silently continuing after a bad command.

#!/bin/bash
set -euo pipefail
# Exit handlers
cleanup() {
local exit_code=$?
if [[ $exit_code -ne 0 ]]; then
echo "Script failed with exit code $exit_code" >&2
fi
}
trap cleanup EXIT
# Error function
error() {
echo "ERROR: $*" >&2
return 1
}
# Validate input
validate_input() {
local file="$1"
[[ -f "$file" ]] || error "File not found: $file"
[[ -r "$file" ]] || error "File not readable: $file"
}
# Retry logic
retry() {
local max_attempts=3
local delay=5
local attempt=1
while [[ $attempt -le $max_attempts ]]; do
if "$@"; then
return 0
fi
echo "Attempt $attempt failed, retrying in $delay seconds..."
sleep $delay
((attempt++))
done
error "Failed after $max_attempts attempts"
}
# Test
validate_input "/etc/passwd" || exit 1
retry curl -sf http://example.com

Interview talking point: “trap cleanup EXIT fires on any exit path and captures the exit status first, so the final code survives to tell you whether the run succeeded.”

What it is: set -e exits on the first failing command, set -x echoes each command as it runs, $? holds the last exit code, and trap runs a handler when an error occurs.

Why it is used: To make scripts fail loudly instead of silently continuing with bad state.

#!/bin/bash
# Exit on error
set -e
# Debug mode
set -x
# Capture exit code
command
echo $?
# Trap errors
trap 'echo "Error on line $LINENO"' ERR
# Custom error
if [ ! -f "$file" ]; then
echo "File not found" >&2
exit 1
fi

Interview talking point: “echo $? must immediately follow the command it checks because any command in between overwrites it, and >&2 sends the message to standard error instead of standard output.”


What it is: A crontab line runs /backup.sh at 2am daily; the script tars /data into a date-named file and then deletes backup files older than 30 days.

Why it is used: Unattended nightly backups with automatic cleanup of old copies.

Terminal window
# Cron job
crontab -e
# Add: 0 2 * * * /backup.sh
# /backup.sh
#!/bin/bash
tar -czpf /backup/$(date +%Y%m%d).tar.gz /data
find /backup -type f -mtime +30 -delete

Interview talking point: “The date +%Y%m%d suffix keeps each night’s archive unique, and the find -mtime +30 -delete step is the retention policy; without it, dated backups slowly fill the disk.”

What it is: crontab -e edits a user schedule with five time fields: 0 2 * * * runs at 2am daily, */5 * * * * every five minutes, 0 0 * * 0 on Sundays.

Why it is used: Scheduling backups, reports, and maintenance unattended.

Terminal window
# Edit crontab
crontab -e
# Examples
# Run daily at 2am
0 2 * * * /backup.sh
# Run every 5 minutes
*/5 * * * * /monitor.sh
# Run on specific days
0 0 * * 0 /weekly.sh
# System cron (runs even if user not logged in)
/etc/cron.d/mycron

Interview talking point: “/etc/cron.d is system cron: it runs without any user logged in and accepts a user field, so daemon schedules belong there while personal scripts stay in a crontab.”


What it is: cron runs jobs on a schedule. crontab -e edits a user’s table of five time fields plus a command, and files under /etc/cron.d add system-wide entries that also name the user to run as.

Why it is used: To automate recurring tasks like backups, cleanups, and reports without manual intervention.

Terminal window
# Edit crontab
crontab -e
# Examples
# Every minute
* * * * * /path/to/script.sh
# Daily at 2am
0 2 * * * /path/to/script.sh
# Weekly on Sunday
0 0 * * 0 /path/to/script.sh
# Every 5 minutes
*/5 * * * * /path/to/script.sh
# System cron
# /etc/cron.d/mycron
*/5 * * * * root /path/to/script.sh

Interview talking point: “The five fields are minute, hour, day of month, month, day of week, so 0 2 * * * is 2am daily and */5 * * * * is every five minutes. /etc/cron.d entries need a username field, while a personal crontab does not.”

What it is: apt refreshes package indexes with update, applies newer versions with upgrade, installs with install, removes with remove or autoremove, and lists packages with list —installed.

Why it is used: To manage packages on Debian and Ubuntu systems.

Terminal window
# Update
apt update
apt upgrade
# Install
apt install package
apt-get install package
# Remove
apt remove package
apt autoremove
# Search
apt search package
# List installed
apt list --installed

Interview talking point: “apt update only downloads the latest package lists while apt upgrade is what actually installs new versions, so running only one of them leaves the machine unpatched.”

What it is: yum and dnf are RPM-based package managers that install, update, search, and remove packages, with dnf also offering autoremove for unneeded dependencies.

Why it is used: To install and patch software on RHEL-family systems.

Terminal window
# Install package
yum install package
dnf install package
# Update
yum update
dnf update
# Search
yum search package
dnf search package
# Remove
yum remove package
dnf autoremove
# List installed
yum list installed
dnf list installed

Interview talking point: “dnf is the modern successor to yum with the same core subcommands, so install, update, search, and list installed transfer directly, and dnf autoremove cleans orphaned dependencies.”

What it is: zypper is the package management tool for SUSE systems, offering install, update, remove, and search subcommands for software on openSUSE and SUSE Enterprise hosts.

Why it is used: To install and update packages on SUSE-based distributions.

Terminal window
# Install
zypper install package
# Update
zypper update
# Remove
zypper remove package
# Search
zypper search package

Interview talking point: “the subcommand names install, update, remove, and search are shared with yum and apt, so the workflow carries across distributions even though the tool itself changes.”

Q56: How do you manage package repositories?

Section titled “Q56: How do you manage package repositories?”

What it is: Repository management: apt reads /etc/apt/sources.list deb lines, add-apt-repository adds a PPA, and apt update refreshes indexes; RHEL reads .repo files under /etc/yum.repos.d, with apt clean or yum purging caches and policy or repolist listing sources.

Why it is used: To control where packages come from and keep index data current.

/etc/apt/sources.list
# Debian/Ubuntu
deb http://archive.ubuntu.com/ubuntu/ jammy main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted universe multiverse
# Add repository
add-apt-repository ppa:nginx/stable
# Update
apt update
# RHEL/CentOS
# /etc/yum.repos.d/*.repo
[baseos]
name=BaseOS
baseurl=https://dl.fedoraproject.org/pub/epel/$releasever/Everything/$basearch
enabled=1
# Clean cache
apt clean
yum clean all
# List repos
apt-cache policy
yum repolist

Interview talking point: “apt update only refreshes package indexes and upgrades nothing, and apt-cache policy shows which repository and version each install candidate would actually come from.”

What it is: yum-config-manager adds an RPM repository URL, while on apt systems add-apt-repository adds a PPA or a deb line is written into /etc/apt/sources.list.d followed by apt update.

Why it is used: To reach software that is not present in the default distribution repositories.

Terminal window
# yum add repo
yum-config-manager --add-repo http://repo.example.com.repo
# apt add repo
add-apt-repository ppa:name/ppa
# or
echo "deb url" > /etc/apt/sources.list.d/file.list
apt update

Interview talking point: “after adding any apt source you must run apt update, since adding the file alone does not refresh the index and the new packages will not appear in searches yet.”


What it is: Rollback options: apt-mark hold pins a package, installing an explicit version downgrades it, apt-clone snapshots installed packages, yum history undo reverses an RPM transaction, and transactional-update supports openSUSE.

Why it is used: To recover quickly when a package update breaks a service.

Terminal window
# Debian/Ubuntu
# Hold package
apt-mark hold apache2
# View installed versions
apt-cache policy nginx
# Downgrade
apt install nginx=1.18.0-*
# Snapshots with apt
apt install apt-clone
apt-clone clone myserver-packages
apt-clone restore myserver-packages.tar.gz
# RPM rollback (RHEL)
# yum history
yum history
yum history undo <transaction-id>
# Transactional updates (openSUSE)
transactional-update

Interview talking point: “yum history undo works because RPM records transactions with IDs, whereas Debian has no built-in undo, so hold and explicit version installs are the practical controls there.”

What it is: System updates use apt update, apt list —upgradable, apt upgrade and apt full-upgrade on Debian, yum update on RHEL, plus unattended-upgrades and live patching.

Why it is used: To keep packages and the kernel patched against vulnerabilities without manual work on every host.

Terminal window
# Debian/Ubuntu
apt update
apt list --upgradable
apt upgrade
apt full-upgrade
# Unattended upgrades
apt install unattended-upgrades
# /etc/apt/apt.conf.d/50unattended-upgrades
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}-security";
};
# RHEL/CentOS
yum update
yum check-update
# Kernel live patching
# Ubuntu
snap install canonical-livepatch
canonical-livepatch enable <token>
# RHEL
yum install kpatch

Interview talking point: “apt update only refreshes the package index while upgrade installs newer versions, full-upgrade may remove packages to resolve dependencies, and canonical-livepatch or kpatch fixes the kernel without a reboot.”

What it is: Download a tarball with wget, extract it with tar -xzvf, run ./configure with —prefix to choose the install location, run make to compile, then make install to place files.

Why it is used: To build and install software that the distribution does not package.

Terminal window
# Download and extract
wget url
tar -xzvf file.tar.gz
# Configure
./configure --prefix=/usr/local
# Build
make
# Install
make install
# or
sudo make install

Interview talking point: “—prefix=/usr/local decides where make install writes, so the same source tree can land in a custom location instead of system paths, which is the point of the configure step.”

Q61: Describe the Linux boot process from power on.

Section titled “Q61: Describe the Linux boot process from power on.”

What it is: Boot runs from BIOS or UEFI POST, to GRUB2 loading the kernel with initramfs, to the kernel mounting root and starting systemd until the expected targets are reached.

Why it is used: To know which stage to check when a machine fails to come up.

Terminal window
# View boot messages
dmesg | less
journalctl -b
# Boot time analysis
systemd-analyze time
systemd-analyze blame | head -20

Interview talking point: “systemd-analyze time gives total boot duration while systemd-analyze blame ranks the slowest units, and journalctl -b reads the current boot’s logs, so timing problems are separated from failing units.”

Q62: What is GRUB2 and how do you configure it?

Section titled “Q62: What is GRUB2 and how do you configure it?”

What it is: GRUB2 is the boot loader that reads its configuration, shows the menu, and loads the kernel. Settings live in /etc/default/grub and regenerate into grub.cfg.

Why it is used: To change kernel parameters, default entries, or boot timeouts, and to recover from a bad entry.

Terminal window
# Edit GRUB config
vim /etc/default/grub
# Common settings
GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_CMDLINE_LINUX="quiet splash"
# Regenerate config
update-grub # Debian/Ubuntu
grub2-mkconfig -o /boot/grub2/grub.cfg # RHEL/CentOS
# GRUB command line
# Press 'e' at boot menu to edit

Interview talking point: “Editing /etc/default/grub does nothing until update-grub or grub2-mkconfig regenerates grub.cfg, and the two distro families use different commands and output paths. Pressing e at the menu edits parameters for one boot only.”

What it is: initramfs is a RAM-based filesystem holding kernel modules needed before the real root filesystem is mounted, then it hands over and is discarded.

Why it is used: To fix missing-driver or failed-root boot problems by rebuilding the image for the running kernel.

Terminal window
# Rebuild initramfs
dracut -f # RHEL/CentOS
update-initramfs -u # Debian/Ubuntu
# View contents
lsinitramfs /boot/initrd.img-$(uname -r)
zcat /boot/initrd.img | cpio -id
# Custom initramfs
# Add to /etc/initramfs-tools/modules

Interview talking point: “dracut -f rebuilds on RHEL while update-initramfs -u does it on Debian, and lsinitramfs or zcat with cpio lets you confirm which modules are actually inside before rebooting.”

What it is: The initramfs is the early boot image holding modules needed before the real root filesystem is available. update-initramfs -u or dracut -f rebuilds it, and lsinitramfs shows what is inside.

Why it is used: Rebuilding the boot image after kernel or module changes so boot still matches the installed kernel.

Terminal window
# Update initramfs
update-initramfs -u
# or
dracut -f
# List modules
lsinitramfs /boot/initrd.img-$(uname -r)

Interview talking point: “update-initramfs is the Debian and Ubuntu tool while dracut -f serves Red Hat family systems, but both rebuild for the running kernel, and lsinitramfs lets you verify contents before rebooting.”

What it is: Secure Boot verifies kernel signatures at boot, and GRUB password protection restricts boot parameter editing.

Why it is used: Prevent unauthorized or tampered boot code from executing on the system.

Terminal window
# Enable UEFI secure boot
# Sign kernel
# 1. Generate keys
openssl req -new -x509 -newkey rsa:2048 -keyout MOK.priv -outform DER -out MOK.der -nodes -days 36500 -subj "/CN=My Secure Boot/"
# 2. Sign kernel
sbsign --key MOK.priv --cert MOK.der /boot/vmlinuz-$(uname -r) --output /boot/vmlinuz-$(uname -r)
# 3. Enroll key
mokutil --import MOK.der
# GRUB password protection
# /etc/grub.d/40_custom
set superusers="admin"
password_pbkdf2 admin grub.pbkdf2.sha512.10000.salt.hash
# Recompile GRUB
update-grub
# Disable USB boot
# BIOS settings or
# /etc/modprobe.d/blacklist.conf
install usb-storage /bin/true

Interview talking point: “Machine Owner Keys (MOK) are enrolled locally to trust custom-signed kernels, ensuring boot integrity.”

What it is: systemd replaces init scripts with declarative unit files describing order, dependencies, startup command, and restart policy, all managed through systemctl.

Why it is used: To define how a service starts, when it starts, and how it recovers from failure.

/etc/systemd/system/myservice.service
# Service unit example
[Unit]
Description=My Service
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/myservice
Restart=on-failure
[Install]
WantedBy=multi-user.target
# Manage service
systemctl enable myservice
systemctl start myservice
systemctl status myservice

Interview talking point: “After=network.target orders startup but does not guarantee the network is fully ready, a common surprise. Restart=on-failure gives automatic recovery that SysVinit scripts had to hand-code, and WantedBy controls which target pulls the service in.”

Q67: What is the role of the init system in Linux?

Section titled “Q67: What is the role of the init system in Linux?”

What it is: init is PID 1, the first process the kernel starts. It starts services in order, manages runlevels or targets, handles shutdown, and adopts orphaned processes.

Why it is used: To explain boot ordering and why PID 1 owns every orphaned child process on the box.

Terminal window
# Systemd (modern)
systemctl status
systemctl list-units --type=service
# SysVinit (legacy)
runlevel
ls -la /etc/rc.d/
# Runit
sv status /service/*

Interview talking point: “systemctl and runlevel describe the same machine in different vocabularies: systemd reports units and targets while SysVinit reports runlevels and rc directories. Runit’s sv status gives per-service state without a central manager.”

Q68: How do you configure systemd network targets?

Section titled “Q68: How do you configure systemd network targets?”

What it is: A systemd target unit groups units into a boot milestone. This file defines a custom myapp.target that requires and follows network-online.target and is wanted by multi-user.target.

Why it is used: To start a set of application units together once networking is actually online at boot.

# Create custom target
cat /etc/systemd/system/myapp.target
[Unit]
Description=My Application Target
Requires=network-online.target
After=network-online.target
[Install]
WantedBy=multi-user.target

Interview talking point: “Requires plus After express different things: one is a dependency, the other is ordering. WantedBy=multi-user.target decides what pulls the target in at boot, while Requires and After ensure network-online.target is present and started first.”

What it is: A systemd unit file with Unit, Service, and Install sections defining description, ordering, user, working directory, start and stop commands, restart policy, and journal output.

Why it is used: To run a custom application as a supervised daemon with automatic restart.

/etc/systemd/system/myservice.service
[Unit]
Description=My Service
After=network.target
[Service]
Type=simple
User=myuser
Group=mygroup
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/start
ExecStop=/opt/myapp/bin/stop
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target

Interview talking point: “Type=simple means systemd treats the service as started the moment ExecStart runs, and Restart=on-failure with RestartSec=10 gives automatic recovery with a deliberate delay.”

What it is: systemd-tmpfiles applies config lines that create directories with set permissions or create symlinks, run manually with create or clean and periodically at boot.

Why it is used: To guarantee runtime directories and permissions exist before services start.

/etc/tmpfiles.d/mydirs.conf
# Create directories with specific permissions
d /var/run/myservice 0755 myuser mygroup -
L /var/run/myservice/link - - - - /var/myservice
# Runtime
systemd-tmpfiles --create
systemd-tmpfiles --clean
# At boot
systemctl enable systemd-tmpfiles-clean.timer

Interview talking point: “The d line creates a directory with owner and mode while the L line makes a link, and the clean verb applies age-based cleanup on the same config.”

What it is: systemctl starts, stops, restarts, checks status, and enables or disables services under systemd, while the service command is the older SysV init interface for start and stop.

Why it is used: To control daemons now and at boot while troubleshooting failures.

Terminal window
# SystemD
systemctl start service
systemctl stop service
systemctl restart service
systemctl status service
systemctl enable service
systemctl disable service
# SysV init
service service_name start
service service_name stop

Interview talking point: “enable decides what starts at boot while start acts immediately, so a service can be running but not enabled, and the service command is the legacy wrapper for the same actions.”


What it is: systemd manages services as units, and systemctl starts, stops, restarts, and checks their status. Enabling a service makes it start at boot; disabling removes it from boot.

Why it is used: Running daemons day to day and deciding what comes up after a reboot.

Terminal window
# Start/stop
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
# Enable/disable boot
systemctl enable nginx
systemctl disable nginx
# Status
systemctl status nginx
systemctl is-active nginx
# List
systemctl list-units --type=service
systemctl list-unit-files --type=service

Interview talking point: “systemctl start or stop affects only the current run, while enable or disable controls the next boot, and status shows both the live state and the boot setting in one view.”

What it is: Debugging systemd means checking unit status, reading that unit’s journal entries, following them live, listing dependencies, and inspecting or clearing failed units.

Why it is used: To find why a service will not start or keeps restarting.

Terminal window
# Check status
systemctl status myservice
journalctl -u myservice
# Follow logs
journalctl -fu myservice
# Debug mode
systemctl edit myservice
# Add:
# [Service]
# Environment=SYSTEMD_LOG_LEVEL=debug
# Check dependencies
systemctl list-dependencies myservice
# Check failed
systemctl --failed
systemctl reset-failed

Interview talking point: “systemctl edit writes an override drop-in instead of editing the package-shipped unit, so your debug settings survive package updates and still apply after daemon-reload.”

What it is: journalctl queries the systemd journal: everything, a time window with —since and —until, priority with -p, a unit with -u, live follow with -f, and total size with —disk-usage.

Why it is used: To search and follow system logs by time, priority, or unit during incident triage.

Terminal window
# View all
journalctl
# Since
journalctl --since "1 hour ago"
journalctl --since "2023-01-01"
# Until
journalctl --until "2023-01-01"
# Priority
journalctl -p err
# Service
journalctl -u nginx
# Follow
journalctl -f
# Disk usage
journalctl --disk-usage

Interview talking point: “Combining a —since window with -u narrows results to one service, -p err filters by severity, and -f streams new entries live just like tail -f on a file.”

What it is: journalctl reads the systemd journal; -u selects a unit, —since filters by time, -p err filters by priority, and -f follows new entries as they arrive.

Why it is used: To query boot and service history from one central store.

Terminal window
# View logs
journalctl
journalctl -u nginx.service
journalctl --since "1 hour ago"
journalctl --since "2023-01-01"
# Priority
journalctl -p err
# Follow
journalctl -f

Interview talking point: “—since accepts both relative phrases like “1 hour ago” and absolute dates, and -p err narrows the output to errors and above instead of scrolling through everything.”


What it is: A timer unit with a daily calendar trigger, persistence, and randomized delay fires a companion oneshot service that runs the backup script.

Why it is used: To schedule recurring jobs with systemd instead of editing crontab.

/etc/systemd/system/mytimer.timer
[Unit]
Description=Run daily backup
[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=1h
[Install]
WantedBy=timers.target
# /etc/systemd/system/mytimer.service
[Unit]
Description=Daily backup job
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh

Interview talking point: “Persistent=true runs the missed job after downtime, and the paired service must be Type=oneshot because each timer trigger expects a single finite execution.”

What it is: A systemd timer unit schedules a companion service unit. OnCalendar sets the time, Persistent runs missed jobs on boot, and the service uses Type=oneshot to run a script to completion.

Why it is used: To schedule recurring jobs with logging, dependencies, and missed-run handling built into systemd.

/etc/systemd/system/mytimer.timer
[Unit]
Description=Run daily at midnight
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
# /etc/systemd/system/mytimer.service
[Unit]
Description=My Timer Job
[Service]
Type=oneshot
ExecStart=/usr/local/bin/myscript.sh

Interview talking point: “Persistent=true means a job missed while the machine was off runs at next boot, something plain cron does not offer. systemd timers also give journalctl output for each run and systemctl list-timers shows the next scheduled execution.”

What it is: systemd resource control sets memory maximums and high watermarks, CPU quota, per-device IO bandwidth caps, and a task limit in the Service section.

Why it is used: To keep one noisy service from starving the rest of the host.

/etc/systemd/system/myservice.service
[Service]
MemoryMax=1G
MemoryHigh=512M
CPUQuota=50%
IOReadBandwidthMax=/dev/sda 1M
IOWriteBandwidthMax=/dev/sda 1M
TasksMax=100
# Apply
systemctl daemon-reload
systemctl restart myservice

Interview talking point: “MemoryHigh throttles the cgroup toward the target while MemoryMax is the hard kill boundary, so the two work together rather than duplicating each other.”


What it is: Kernel modules are loadable pieces of the kernel. lsmod lists loaded ones, modinfo shows metadata and parameters, modprobe loads and unloads with dependency handling, and files under modprobe.d set options or blacklists persistently.

Why it is used: To add or remove kernel functionality at runtime and set module options across boots.

Terminal window
# List modules
lsmod
modinfo module_name
# Load module
modprobe module_name
# Unload module
modprobe -r module_name
# Module parameters
modprobe module_name parameter=value
# Persistent configuration
# /etc/modprobe.d/blacklist.conf
blacklist module_name
# /etc/modprobe.d/module.conf
options module_name parameter=value
# Create module dependency
depmod -a
# View module info
modinfo -p module_name

Interview talking point: “modprobe resolves dependencies and reads modprobe.d config, unlike the lower-level insmod, and depmod -a rebuilds the module dependency map after module files change.”

Q80: How do you configure kernel modules at startup?

Section titled “Q80: How do you configure kernel modules at startup?”

What it is: Kernel modules can be auto-loaded at boot and configured through files in /etc/modules and /etc/modprobe.d.

Why it is used: Ensure required drivers load consistently with correct parameters.

/etc/modules
# Load module at boot
loop
st
8021q
# Module parameters
# /etc/modprobe.d/.conf
options bonding mode=active-backup
options iptables conntrack_hashsize=262144
# Blacklist module
# /etc/modprobe.d/blacklist.conf
blacklist nouveau
blacklist snd_pcsp
# Create module dependencies
depmod -a
# View loaded modules
lsmod

Interview talking point: “Blacklisting prevents conflicting modules from loading, and depmod rebuilds dependencies after changing module configuration.”

What it is: A loadable kernel module with init_module and cleanup_module functions, built against the running kernel’s build tree and loaded as a .ko file.

Why it is used: To run code inside the kernel without compiling and rebooting a whole new kernel.

hello.c
#include <linux/module.h>
#include <linux/kernel.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Author");
MODULE_DESCRIPTION("Hello World Module");
int init_module(void) {
printk(KERN_INFO "Hello World!\n");
return 0;
}
void cleanup_module(void) {
printk(KERN_INFO "Goodbye World!\n");
}
# Makefile
obj-m += hello.o
KDIR := /lib/modules/$(shell uname -r)/build
all:
make -C $(KDIR) M=$(PWD) modules
clean:
make -C $(KDIR) M=$(PWD) clean
# Build
make
# Load
insmod hello.ko
# Unload
rmmod hello
# Check
lsmod | grep hello
dmesg | tail

Interview talking point: “insmod loads the module, lsmod confirms it is listed, and dmesg shows the printk output, so a misbehaving module can be removed with rmmod instead of rebooting.”

What it is: Kernel modules are loadable parts of the kernel. lsmod lists loaded modules, modprobe loads or removes one, modinfo shows its details, and a blacklist line stops a module from loading.

Why it is used: Adding hardware or feature support on demand and disabling modules that misbehave.

Terminal window
# List loaded
lsmod
# Load module
modprobe module_name
# Unload module
modprobe -r module_name
# View module info
modinfo module_name
# Blacklist
echo "blacklist module_name" >> /etc/modprobe.d/blacklist.conf

Interview talking point: “modprobe -r removes a module by name and honors dependencies, while adding blacklist module_name to /etc/modprobe.d/blacklist.conf keeps that module from loading on future boots.”

Q83: How do you recover from forgotten root password?

Section titled “Q83: How do you recover from forgotten root password?”

What it is: This is the procedure for regaining root access on a Linux system when the root password has been forgotten and no other administrator login is available.

Why it is used: Escaping a lockout on a machine where no working administrator credentials remain.

# Boot into recovery mode
# 1. Restart system
# 2. Press Shift during boot
# 3. Select "Advanced options"
# 4. Select recovery mode
# 5. Select "root"
# Mount filesystem
mount -o remount,rw /
# Change password
passwd root
# Reboot
reboot

Interview talking point: “In an interview, note that the reset requires physical or console access to the machine, which is why a second admin account or a documented reset path matters before a lockout happens.”


Q84: How do you recover from forgotten root password?

Section titled “Q84: How do you recover from forgotten root password?”

What it is: Recovering from a forgotten root password means obtaining a root shell during boot so the usual authentication step is skipped.

Why it is used: To regain administrative access when the root password is lost and no other privileged account is available.

# Method 1: Single user mode
1. Reboot system
2. Press 'e' at GRUB menu
3. Add 'single' or 'init=/bin/bash' to linux line
4. Press Ctrl+X to boot
5. mount -o remount,rw /
6. passwd root
7. exec /sbin/init
# Method 2: Using rescue disk
1. Boot from rescue media
2. Mount filesystem
3. chroot /mnt/sysimage
4. passwd root
5. exit
6. reboot

Interview talking point: “Because the reset happens at the bootloader before authentication, you get a shell with no password prompt, set a fresh root password, then reboot into the normal runlevel.”

What it is: smartctl -a dumps a drive’s SMART data and -H gives the overall health verdict, df and du show capacity, and iostat -x and iotop report I/O activity.

Why it is used: To catch a failing drive early and find which device is saturating.

Terminal window
# SMART status
smartctl -a /dev/sda
smartctl -H /dev/sda
# Disk usage
df -h
du -sh /*
# I/O stats
iostat -x 1
iotop

Interview talking point: “smartctl -H is the quick pass or fail check while -a lists every attribute, and iostat -x 1 gives per-device utilization every second to spot a saturated disk.”


What it is: Migrating to a new disk means pvcreate on it, vgextend to add it to the volume group, pvmove to shift extents off the old disk, and vgreduce to drop it.

Why it is used: Replace a failing or small disk while the logical volume stays online.

Terminal window
# Create new PV
pvcreate /dev/sdc1
# Add to VG
vgextend vg_name /dev/sdc1
# Move data
pvmove /dev/sdb1 /dev/sdc1
# Remove old
vgreduce vg_name /dev/sdb1

Interview talking point: “pvmove relocates extents while the LV is in use, and it must run before vgreduce, since removing a PV that still holds extents would leave the volume group short of space.”

Q87: How do you create and manage partitions?

Section titled “Q87: How do you create and manage partitions?”

What it is: fdisk -l, lsblk, and parted -l list disks and partitions; fdisk creates one with n, p, w; mkfs.ext4 or mkfs.xfs formats it; mount attaches it to a directory.

Why it is used: To add new storage and make it usable for files.

Terminal window
# List partitions
fdisk -l
lsblk
parted -l
# Create partition
fdisk /dev/sdb
# n (new), p (primary), w (write)
# Format
mkfs.ext4 /dev/sdb1
mkfs.xfs /dev/sdb1
# Mount
mount /dev/sdb1 /mnt/data

Interview talking point: “creating the partition is only step one, since mkfs gives it a filesystem and mount attaches it, so all three steps are needed before anything can be written.”

What it is: dd copies raw data between devices and files block by block. It clones one disk to another, writes a disk image, restores it, zeroes a device, and with a fixed count and direct output flag measures write speed.

Why it is used: To image disks, wipe them, or benchmark raw write throughput on a device.

Terminal window
# Clone disk
dd if=/dev/sda of=/dev/sdb bs=4M status=progress
# Create image
dd if=/dev/sda of=/backup/sda.img bs=4M status=progress
# Restore
dd if=/backup/sda.img of=/dev/sda bs=4M status=progress
# Zero disk
dd if=/dev/zero of=/dev/sda bs=1M status=progress
# Test speed
dd if=/dev/zero of=/tmp/test bs=1G count=1 oflag=direct

Interview talking point: “dd writes straight to its output target with no confirmation, so if and of deserve a second look; bs sets block size while status=progress keeps a long copy visible.”

Q89: How do you configure encrypted partitions?

Section titled “Q89: How do you configure encrypted partitions?”

What it is: LUKS encrypts a whole partition. cryptsetup luksFormat writes the header, cryptsetup open maps it to /dev/mapper/crypt_vol, and that mapper device is then formatted and mounted like any other volume.

Why it is used: To protect data at rest on servers and removable drives if the disk is lost or stolen.

Terminal window
# Create LUKS
cryptsetup luksFormat /dev/sdb1
# Open
cryptsetup open /dev/sdb1 crypt_vol
# Format
mkfs.ext4 /dev/mapper/crypt_vol
# Mount
mount /dev/mapper/crypt_vol /mnt/data
# Close
umount /mnt/data
cryptsetup close crypt_vol
# Auto mount
# /etc/crypttab
crypt_vol /dev/sdb1 none luks

Interview talking point: “You format and mount /dev/mapper/crypt_vol rather than /dev/sdb1, because the mapper device is the decrypted view of the partition. cryptsetup close destroys the active mapping and key, and /etc/crypttab makes the mapping available again at boot.”


What it is: LUKS encrypts a partition: cryptsetup luksFormat initializes it, luksOpen maps it to /dev/mapper/crypt_vol, then mkfs.ext4 and mount work on the mapper device until luksClose.

Why it is used: Protecting data at rest on disks that could be lost or stolen.

Terminal window
# LUKS encryption
cryptsetup luksFormat /dev/sdb1
cryptsetup luksOpen /dev/sdb1 crypt_vol
mkfs.ext4 /dev/mapper/crypt_vol
mount /dev/mapper/crypt_vol /mnt/data
# Close
umount /mnt/data
cryptsetup luksClose crypt_vol

Interview talking point: “Everything after luksOpen happens on /dev/mapper/crypt_vol rather than /dev/sdb1, and once cryptsetup luksClose runs the raw partition is unreadable without the passphrase.”


Q91: What is the difference between ext4 and XFS?

Section titled “Q91: What is the difference between ext4 and XFS?”

What it is: ext4 and XFS are journaling filesystems; ext4 caps files at 16TB and suits small files, while XFS reaches 8EB, handles large files well, and resizes online.

Why it is used: To pick a filesystem matching file sizes, growth plans, and resize needs.

Terminal window
# Create ext4
mkfs.ext4 -j /dev/sdb1
# Create XFS
mkfs.xfs -f /dev/sdb1
# Tune ext4
tune2fs -o journal_data /dev/sda1
tune2fs -O dir_index /dev/sda1

Interview talking point: “mkfs.ext4 -j enables the journal while mkfs.xfs -f forces overwriting an existing filesystem. tune2fs tunes ext4 features like journal_data and dir_index after the fact, in a way XFS does not provide.”

What it is: Dedup is enabled per dataset with zfs set dedup=on, the ratio is checked with zpool status -D, and an algorithm can be chosen such as sha256 with verification.

Why it is used: Save space when the same block appears many times, like identical VM images.

Terminal window
# Enable dedup
zfs set dedup=on pool1/data
# Check dedup ratio
zpool status -D pool1
# With specific algorithm
zfs set dedup=sha256,verify pool1/data

Interview talking point: “The dedup setting is chosen at write time and affects the pool’s memory use, so zpool status -D reports the realized ratio rather than an estimate computed after the fact.”

Q93: How do you create and manage ext4 filesystem?

Section titled “Q93: How do you create and manage ext4 filesystem?”

What it is: mkfs.ext4 creates an ext4 filesystem on a partition, while tune2fs adjusts its tuneable parameters such as check frequency. e2fsck verifies it and resize2fs grows or shrinks it.

Why it is used: To format, maintain, check, and resize ext4 partitions, the default filesystem on most Linux distributions.

Terminal window
# Create ext4
mkfs.ext4 /dev/sdb1
# With options
mkfs.ext4 -T largefile -m 0 /dev/sdb1
# Tune
tune2fs -c 30 /dev/sdb1 # check every 30 mounts
tune2fs -i 30d /dev/sdb1 # check every 30 days
# Check
e2fsck -f /dev/sdb1
# Resize
resize2fs /dev/sdb1 # to fill partition
resize2fs /dev/sdb1 10G # shrink to 10G

Interview talking point: “tune2fs -c sets checks by mount count while -i sets an interval in days, and e2fsck -f forces a full check regardless of those settings. resize2fs takes the device and can shrink it to a size such as 10G.”

What it is: mkfs.btrfs creates a btrfs filesystem, optionally labeling it and laying out data and metadata across devices in RAID levels. Subvolumes are created inside it and can be snapshotted.

Why it is used: To get copy-on-write storage with snapshots, compression, and multi-device RAID from the filesystem itself.

Terminal window
# Create
mkfs.btrfs -L mydata /dev/sdb
# RAID levels
mkfs.btrfs -d raid1 -m raid1 /dev/sdb /dev/sdc
# Subvolumes
mount /dev/sdb /mnt/btrfs
btrfs subvolume create /mnt/btrfs/vol1
# Snapshots
btrfs subvolume snapshot /mnt/btrfs/vol1 /mnt/btrfs/snap1
# Properties
btrfs property set /mnt/btrfs/vol1 compression zstd

Interview talking point: “A snapshot is an inexpensive copy-on-write clone, so snap1 is created almost instantly, and compression is enabled per subvolume with btrfs property set compression zstd rather than at format time.”

What it is: mkfs.xfs creates an XFS filesystem, with -f forcing an overwrite and options controlling allocation groups and log size. xfs_repair checks or repairs it, and xfs_growfs extends it.

Why it is used: To lay out and maintain XFS, widely used for large data volumes on enterprise Linux.

Terminal window
# Create XFS
mkfs.xfs /dev/sdb1
# With options
mkfs.xfs -f -d agcount=4 -l size=100m /dev/sdb1
# Check
xfs_repair /dev/sdb1
# Grow
xfs_growfs /mount/point
# Repair
xfs_repair -n /dev/sdb1 # just check

Interview talking point: “xfs_repair -n runs a read-only check that does not modify the device, and xfs_growfs is pointed at a mount point rather than the block device, unlike resize2fs which takes the device.”

What it is: A balance rewrites block groups across a mounted filesystem, run with btrfs balance start, optionally converting data and metadata to raid1 or filtering with -dusage, and watched with balance status.

Why it is used: Reclaim space from partly used chunks or change storage profile after adding disks.

Terminal window
# Full balance
btrfs balance start /mnt/btrfs
# Specific profile
btrfs balance start -dconvert=raid1 -mconvert=raid1 /mnt/btrfs
# With filters
btrfs balance start -dusage=50 /mnt/btrfs
# Status
btrfs balance status /mnt/btrfs

Interview talking point: “-dconvert changes the data profile and -mconvert the metadata profile, and filters like -dusage=50 limit the work to chunks below that usage so a balance does not rewrite everything.”

What it is: btrfs RAID1 is enabled by balancing data and metadata to raid1 after adding a device with btrfs device add, and a disk is dropped with btrfs device remove.

Why it is used: Mirror a filesystem across two disks and grow it by swapping in larger ones.

Terminal window
# Convert to RAID1
btrfs balance start -dconvert=raid1 -mconvert=raid1 /mnt/btrfs
# Add device
btrfs device add /dev/sdc1 /mnt/btrfs
# Remove device
btrfs device remove /dev/sdb1 /mnt/btrfs

Interview talking point: “Adding a device does not change the profile by itself, so the balance with -dconvert=raid1 is the step that actually starts mirroring, and removal must happen after data is rebalanced off it.”

What it is: btrfs send streams a read-only snapshot, optionally incremental with -p naming a parent snapshot, piped through gzip into a file, and btrfs receive replays that stream into a filesystem.

Why it is used: Ship filesystem snapshots off host for backups or cloning, efficiently with incrementals.

Terminal window
# Initial backup
btrfs send /mnt/snap1 | gzip > backup1.gz
# Incremental
btrfs send -p /mnt/snap1 /mnt/snap2 | gzip > backup2.gz
# Receive
gzip -d -c backup2.gz | btrfs receive /backup/

Interview talking point: “The -p parent tells send to emit only the difference, which is why the incremental backup is far smaller than the initial one, and both snapshots must be read-only.”

What it is: Btrfs is a copy-on-write filesystem. mkfs.btrfs formats a device, subvolumes are created and listed like directories, snapshots copy a subvolume, balance redistributes data, compress=zstd mounts with compression, and raid1 gives redundancy.

Why it is used: To get snapshots, compression and RAID from one filesystem without separate volume management.

Terminal window
# Create btrfs
mkfs.btrfs -L mydata /dev/sdb
# Mount
mount /dev/sdb /mnt/btrfs
# Subvolumes
btrfs subvolume create /mnt/btrfs/data
btrfs subvolume list /mnt/btrfs
# Snapshots
btrfs subvolume snapshot /mnt/btrfs/data /mnt/btrfs/snap
# Balance
btrfs balance start /mnt/btrfs
# Compression
mount -o compress=zstd /dev/sdb /mnt/btrfs
# RAID
mkfs.btrfs -d raid1 -m raid1 /dev/sdb /dev/sdc

Interview talking point: “Subvolumes are not partitions: btrfs subvolume snapshot makes a writable copy instantly, so the data and snap paths coexist on the same filesystem, and mkfs.btrfs -d raid1 -m raid1 spreads data and metadata across two disks.”

What it is: zfs send streams a snapshot to another host where zfs receive recreates it, with -i making the transfer incremental from one snapshot to the next and gzip compressing the pipe.

Why it is used: Replicate datasets to another machine for backup or migration over a network.

Terminal window
# Full send
zfs send pool1/data@snap1 | ssh host "zfs receive pool1/data"
# Incremental
zfs send -i pool1/data@snap1 pool1/data@snap2 | ssh host "zfs receive pool1/data"
# Compressed
zfs send pool1/data@snap1 | gzip | ssh host "gunzip | zfs receive pool1/data"

Interview talking point: “send and receive are pipes, so the source only needs to stream while the remote runs receive, and -i turns a full copy into just the delta between two snapshots.”