Linux_Practical_Interview_1 100
Linux Practical Interview Questions (1-100)
Section titled “Linux Practical Interview Questions (1-100)”Level 1: Linux Fundamentals
Section titled “Level 1: Linux Fundamentals”Linux Concepts and Architecture
Section titled “Linux Concepts and Architecture”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.
# System call interface# User space -> libc -> system call wrapper -> kernel# Example: read() system callssize_t read(int fd, void *buf, size_t count);
# View system callsstrace -e trace=read,write cat /etc/passwd
# List system callsman syscalls# orcat /usr/include/asm/unistd_64.h | head -30Interview 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.”
System Information Basics
Section titled “System Information Basics”Q2: How do you check CPU information?
Section titled “Q2: How do you check CPU information?”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.
# CPU infocat /proc/cpuinfo# orlscpu# ortopInterview 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.”
Q3: How do you check system uptime?
Section titled “Q3: How do you check system uptime?”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.
# Check uptimeuptime# oruptime -p # pretty format# orcat /proc/uptimeInterview 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.
# Check kernel versionuname -r# orcat /proc/version# orhostnamectlInterview 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.”
Input, Output, Pipes, and Redirection
Section titled “Input, Output, Pipes, and Redirection”Q5: How do you use named pipes?
Section titled “Q5: How do you use named pipes?”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.
# Create named pipemkfifo /tmp/myfifo
# In one terminal (read)cat < /tmp/myfifo
# In another terminal (write)echo "Hello" > /tmp/myfifo
# Process substitutiondiff <(sort file1) <(sort file2)
# While readingwhile read line; do echo "$line"; done < /tmp/myfifoInterview 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.”
Level 2: Filesystem and File Operations
Section titled “Level 2: Filesystem and File Operations”Permissions and Ownership
Section titled “Permissions and Ownership”Q6: How do special permissions work?
Section titled “Q6: How do special permissions work?”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.
# 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 bitchmod 1777 /tmp # or chmod +t /tmp
# Viewls -l file # shows s or tInterview 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.”
Q7: How do you manage file permissions?
Section titled “Q7: How do you manage file permissions?”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.
# Change permissionschmod 755 filechmod +x script.shchmod -R 644 directory/
# Change ownerchown user:group file
# View permissionsls -l fileInterview 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.”
Disk Usage Basics
Section titled “Disk Usage Basics”Q8: How do you check disk usage?
Section titled “Q8: How do you check disk usage?”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.
# Disk usagedf -h# ordu -sh /path/to/directory# orlsblkInterview 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.”
Searching Files
Section titled “Searching Files”Q9: How do you find files in Linux?
Section titled “Q9: How do you find files in Linux?”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.
# Find filesfind /path -name "filename"# Find by typefind /path -type f -name "*.log"# Find by sizefind /path -size +100M# Find by modified timefind /path -mtime -7Interview 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.”
Q10: How do you search inside files?
Section titled “Q10: How do you search inside 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.
# Search in filesgrep -r "search_term" /path# Case insensitivegrep -ri "search_term" /path# Show line numbersgrep -n "search_term" file# Use regexgrep -E "pattern" fileInterview 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.”
Archives and Compression
Section titled “Archives and Compression”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.
# gzip compressiongzip filegunzip file.gz
# tar archivetar -cvf archive.tar directory/tar -xvf archive.tartar -czvf archive.tar.gz directory/tar -xzvf archive.tar.gz
# zipzip -r archive.zip directory/unzip archive.zipInterview 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.”
Q12: How do you use tar for backups?
Section titled “Q12: How do you use tar for backups?”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.
# Create archivetar -cvf backup.tar /datatar -cvzf backup.tar.gz /datatar -cvjf backup.tar.bz2 /data
# Extracttar -xvf backup.tartar -xvzf backup.tar.gz
# List contentstar -tvf backup.tar
# Incremental backuptar -g /var/log/backup.snap -cvzf backup-incremental.tar.gz /data
# With datetar -cvzf backup-$(date +%Y%m%d).tar.gz /dataInterview 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.”
Q13: How do you use tar?
Section titled “Q13: How do you use tar?”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.
# Create archivetar -cvf archive.tar file1 file2 directory/
# With compressiontar -czvf archive.tar.gz directory/tar -cjvf archive.tar.bz2 directory/tar -cJvf archive.tar.xz directory/
# Extracttar -xvf archive.tartar -xzvf archive.tar.gztar -xjvf archive.tar.bz2
# Listtar -tvf archive.tarInterview 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.”
Level 3: Users, Groups, and Privileges
Section titled “Level 3: Users, Groups, and Privileges”Users and Accounts
Section titled “Users and Accounts”Q14: How do you create and manage users?
Section titled “Q14: How do you create and manage users?”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.
# Create useruseradd username# or with home directoryuseradd -m username
# Set passwordpasswd username
# Add to groupusermod -aG groupname username
# Delete useruserdel username
# Check user infoid usernameInterview 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.”
Sessions and Login Activity
Section titled “Sessions and Login Activity”Q15: How do you check user sessions?
Section titled “Q15: How do you check user sessions?”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.
# Who is logged inwhow# Last loginlastlastlog# Current userwhoamiInterview 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.”
Sudo and Privilege Management
Section titled “Sudo and Privilege Management”Q16: How do you configure sudo access?
Section titled “Q16: How do you configure sudo access?”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.
# Edit sudoersvisudo
# Grant all privilegesusername ALL=(ALL:ALL) ALL
# Passwordlessusername ALL=(ALL) NOPASSWD: ALL
# Specific commandsusername ALL=(ALL) /bin/ls, /bin/kill
# Group%sudo ALL=(ALL:ALL) ALLInterview 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.”
Q17: How do you use sudo configuration?
Section titled “Q17: How do you use sudo configuration?”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.
# Edit sudoers filevisudo
# Grant sudo accessusername ALL=(ALL:ALL) ALL
# Passwordless sudousername ALL=(ALL) NOPASSWD: ALLInterview 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.”
Password and Authentication Basics
Section titled “Password and Authentication Basics”Q18: How do you lock/unlock accounts?
Section titled “Q18: How do you lock/unlock accounts?”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.
# Lock accountusermod -L username# orpasswd -l username
# Unlockusermod -U username# orpasswd -u username
# Check statuspasswd -S usernameInterview 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.”
Q19: How do you set up password policies?
Section titled “Q19: How do you set up password policies?”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.
# PAM configurationPASS_MAX_DAYS 90PASS_MIN_DAYS 1PASS_MIN_LEN 12PASS_WARN_AGE 7
# Or using chage# Set password expirationchage -M 90 usernamechage -m 1 usernamechage -W 7 username
# Viewchage -l usernameInterview 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.”
Bulk User Management
Section titled “Bulk User Management”Q20: How do you manage groups in bulk?
Section titled “Q20: How do you manage groups in bulk?”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.
# Create groupsfor group in group1 group2 group3; do groupadd "$group"done
# Add users to groupgpasswd -M user1,user2,user3 groupname
# Add users one by onefor user in user1 user2; do usermod -aG groupname "$user"doneInterview 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.”
Q21: How do you manage users in bulk?
Section titled “Q21: How do you manage users in bulk?”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.
# Create users from filewhile 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 bulkfor user in user1 user2 user3; do echo "$user:password" | chpasswddone
# CSV import# username,uid,gid,info,home,shell,passwordInterview 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.”
Level 4: Processes and Job Control
Section titled “Level 4: Processes and Job Control”Process Inspection
Section titled “Process Inspection”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.
# CPU and memorytophtop# Per-processps aux --sort=-%cpu | headps aux --sort=-%mem | head# Detailed/proc/PID/statusInterview 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.”
Q23: How do you view running processes?
Section titled “Q23: How do you view running processes?”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.
# View processespsps auxps -ef# Interactivetophtop# Tree viewpstreeInterview 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.”
Q24: How do you use htop?
Section titled “Q24: How do you use htop?”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.
# Installapt install htop
# Runhtop
# Optionshtop -u userhtop -p PID1,PID2
# Interactive# F3: search# F4: filter# F5: tree# F6: sort# F9: killInterview 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.”
Signals and Termination
Section titled “Signals and Termination”Q25: How do you kill processes?
Section titled “Q25: How do you kill processes?”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.
# Kill by PIDkill -15 pid # SIGTERM (graceful)kill -9 pid # SIGKILL (force)kill -2 pid # SIGINT (Ctrl+C)
# Kill by namepkill process_namekillall process_name
# Kill processes by patternpgrep pattern | xargs killInterview 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.”
Jobs and Background Execution
Section titled “Jobs and Background Execution”Q26: How do you manage background jobs?
Section titled “Q26: How do you manage background jobs?”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.
# Run in backgroundcommand &
# List jobsjobs
# Bring to foregroundfg %1
# Send to backgroundCtrl+Zbg %1
# Run nohupnohup 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.”
Level 5: Shell and Bash
Section titled “Level 5: Shell and Bash”Variables and Scope
Section titled “Variables and Scope”Q27: How do you use arrays?
Section titled “Q27: How do you use arrays?”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.
# Define arrayarr=(one two three)arr[0]="one"
# Access elementsecho ${arr[0]}echo ${arr[@]}
# Lengthecho ${#arr[@]}
# Loopfor item in "${arr[@]}"; do echo $itemdone
# Add elementsarr+=("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.”
Q28: How do you use string operations?
Section titled “Q28: How do you use string operations?”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.
# 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.”
Functions and Parameters
Section titled “Functions and Parameters”Q29: How do you handle arguments?
Section titled “Q29: How do you handle arguments?”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# Argumentsecho $0 # Script nameecho $1 # First argumentecho $# # Number of argumentsecho $@ # All argumentsecho $$ # PID
# Loop through argumentsfor arg in "$@"; do echo $argdone
# Getoptswhile getopts "hvc:" opt; do case $opt in h) echo "Help";; v) echo "Version";; c) echo "Config: $OPTARG";; esacdoneInterview 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.”
Text Processing
Section titled “Text Processing”Q30: How do you parse CSV in bash?
Section titled “Q30: How do you parse CSV in bash?”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.
# Basic parsingwhile IFS=',' read -r col1 col2 col3; do echo "$col1 $col2 $col3"done < file.csv
# Skip headertail -n +2 file.csv | while IFS=',' read -r col1 col2 col3; do echo "$col1 $col2 $col3"done
# Using awkawk -F',' '{print $1,$2}' file.csv
# With headersawk -F',' 'NR==1 {for(i=1;i<=NF;i++) h[$i]=i} NR>1 {print $h["name"],$h["age"]}' file.csvInterview 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.”
Q31: How do you parse JSON in bash?
Section titled “Q31: How do you parse JSON in bash?”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.
# Using jqapt install jq
# Parse JSONecho '{"name":"John","age":30}' | jq '.name'echo '{"users":["Alice","Bob"]}' | jq '.users[0]'
# Conditionalecho '{"status":"ok"}' | jq 'if .status == "ok" then "success" else "failed" end'
# Modifyecho '{"name":"John"}' | jq '.age = 30'
# From filejq '.users[]' data.json
# With variablesNAME=$(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.”
Q32: How do you parse JSON in bash?
Section titled “Q32: How do you parse JSON in bash?”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.
# Using jq# Parse JSONcat data.json | jq '.name'cat data.json | jq '.items[].value'
# Filtercat data.json | jq '.items[] | select(.id > 5)'
# Transformcat data.json | jq '{name: .name, computed: .value * 2}'
# Arrayscat data.json | jq '.items | length'cat data.json | jq '.items | map(.name)'
# Create JSONjq -n '{name: "test", items: [1,2,3]}'
# Modifyjq '.name = "new"' data.jsonjq '.items += ["new"]' data.json
# Input from variabledata='{"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.”
Q33: How do you parse JSON in bash?
Section titled “Q33: How do you parse JSON in bash?”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.
# Using jqcat data.json | jq '.name'cat data.json | jq '.items[].value'cat data.json | jq '.items[] | select(.id > 5)'
# Create JSONjq -n '{name: "test", items: [1,2,3]}'
# Modifyjq '.name = "new"' data.json
# Filterjq '.items[] | select(.age > 25)' data.jsonInterview 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.”
Q34: How do you process JSON in bash?
Section titled “Q34: How do you process JSON in bash?”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.
# Using jqcat 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 JSONjq -n '{name: "test", value: 42}'
# Modify JSONcat data.json | jq '.name = "new_name"'cat data.json | jq '.items += [{"id": 3}]'
# Filtercat 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.
# Print columnsawk '{print $1}' file# Field separatorawk -F',' '{print $2}' file# Conditionalawk '$3 > 50 {print $1}' file# Sum valuesawk '{sum+=$1} END {print sum}' fileInterview 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.
# Basic usageawk '{print $1}' file.txtawk -F: '{print $1, $6}' /etc/passwd
# Conditionalawk '$3 > 1000 {print $1, $3}' /etc/passwd
# Calculationsawk '{sum+=$1} END {print sum}' numbers.txt
# Multiple fieldsawk '{print "User:" $1 " UID:" $3 " Home:" $6}' /etc/passwd
# Patternsawk '/^root/ {print}' /etc/passwdawk 'NR==5 {print}' file.txt
# Field separatorawk -F: '{print NF}' /etc/passwdInterview 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.”
Q37: How do you use awk?
Section titled “Q37: How do you use awk?”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.
# Basicawk '{print $1}' file.txt
# Field separatorawk -F: '{print $1, $6}' /etc/passwd
# Conditionalawk '$3 > 1000 {print $1, $3}' /etc/passwd
# Calculationsawk '{sum+=$1} END {print sum}' numbers.txt
# Patternsawk '/ERROR/ {print}' logfile
# Multiple fieldsawk '{for(i=1;i<=NF;i++) sum[i]+=$i} END {for(i in sum) print i, sum[i]}' file.txtInterview 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.”
Q38: How do you use process substitution?
Section titled “Q38: How do you use process substitution?”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.
# Compare two command outputsdiff <(command1) <(command2)
# Read from multiple fileswhile read line; do echo "$line"; done < <(cat file1 file2)
# Feed output to command expecting filegrep pattern <(echo "line with pattern")
# Multiple inputscomm <(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.”
Q39: How do you use regex in scripts?
Section titled “Q39: How do you use regex in scripts?”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.
# Extract IP addressesgrep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' file.txt
# Validate emailemail="user@example.com"if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then echo "Valid"fi
# Extract datesgrep -oE '[0-9]{4}-[0-9]{2}-[0-9]{2}' file.txt
# Replace with sedsed -E 's/([0-9]{4})([0-9]{2})([0-9]{2})/\1-\2-\3/g' file.txt
# Using awkawk '/pattern/ {print $1, $2}' file.txtawk 'match($0, /[0-9]+/) {print substr($0, RSTART, RLENGTH)}' file.txt
# Complex parsingawk 'BEGIN { FPAT = "([^,]+)|(\"[^\"]+\")" }{ for (i=1; i<=NF; i++) { gsub(/^"|"$/, "", $i) print i ": " $i }}' data.csvInterview 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.
# Replace textsed 's/old/new/' file.txtsed 's/old/new/g' file.txtsed 's/old/new/2' file.txt
# In-place editingsed -i 's/old/new/g' file.txt
# Delete linessed '/pattern/d' file.txtsed '1,5d' file.txtsed '5d' file.txt
# Insert textsed '1i\Header line' file.txtsed '1a\New line' file.txt
# Regexsed -E 's/[0-9]+/[REDACTED]/g' file.txtInterview 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.
# Replace textsed 's/old/new/g' file# In-place editsed -i 's/old/new/g' file# Delete linessed '/pattern/d' file# Print specific linesed -n '5p' fileInterview 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.”
Q42: How do you use sed?
Section titled “Q42: How do you use sed?”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.
# Replacesed 's/old/new/' file.txtsed 's/old/new/g' file.txtsed -i 's/old/new/g' file.txt
# Delete linessed '/pattern/d' file.txtsed '1,5d' file.txt
# Insertsed '1i\Header' file.txt
# Regexsed -E 's/[0-9]{4}/[REDACTED]/g' file.txt
# In-place with backupsed -i.bak 's/old/new/g' file.txtInterview 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.”
Q43: How do you use xargs?
Section titled “Q43: How do you use xargs?”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.
# Find and deletefind /tmp -type f -name "*.tmp" -exec rm {} \;# Equivalent using xargsfind /tmp -type f -name "*.tmp" | xargs rm
# Parallel processingls *.jpg | xargs -n 1 -P 4 convert -resize 800x600
# With custom delimiterecho "a:b:c" | xargs -d ':' -n1
# Prompt before executionls | xargs -p rmInterview 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.”
Shell Scripting
Section titled “Shell Scripting”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
# VariablesNAME="John"echo "Hello $NAME"
# User inputread -p "Enter name: " NAME
# Conditionalsif [ "$NAME" == "John" ]; then echo "Hello John"fi
# Loopsfor i in {1..5}; do echo $idone
# Functionsfunction 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/bashset -euo pipefail
# Use functionslog() { echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*"}
# Parse argumentswhile getopts "hvf:" opt; do case $opt in h) help; exit 0 ;; v) VERBOSE=1 ;; f) FILE="$OPTARG" ;; *) exit 1 ;; esacdone
# Use arraysfiles=("file1" "file2" "file3")for file in "${files[@]}"; do process "$file"done
# Error handlingtrap 'echo "Error on line $LINENO"' ERRInterview 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/bashset -euo pipefailIFS=$'\n\t'
# Use functionslog() { echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*"}
# Use arraysfiles=("file1" "file2" "file3")for file in "${files[@]}"; do [[ -f "$file" ]] || continue process "$file"done
# Process efficientlywhile IFS= read -r line; do ((count++))done < <(grep -r "pattern" .)
# Parallel processingparallel -j 4 process {} ::: *.logInterview 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.”
Q47: How do you write efficient scripts?
Section titled “Q47: How do you write efficient scripts?”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/bashset -euo pipefailIFS=$'\n\t'
# Use arrays for loopsfiles=( /var/log/*.log )for file in "${files[@]}"; do [[ -f "$file" ]] || continue process "$file"done
# Use functions with local variablesprocess() { local file="$1" local content content=$(<"$file") echo "${content:0:100}"}
# Avoid subshells in loopswhile IFS= read -r line; do ((count++))done < <(grep -r "pattern" .)
# Use coprocessescoproc BC { bc -l; }echo "scale=10; 355/113" >&${BC[1]}read -r pi <&${BC[0]}
# Use process substitutiondiff <(sort file1) <(sort file2)
# Parallel processingparallel -j 4 process {} ::: *.logInterview 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.”
Q48: How do you handle errors in scripts?
Section titled “Q48: How do you handle errors in scripts?”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/bashset -euo pipefail
# Exit handlerscleanup() { local exit_code=$? if [[ $exit_code -ne 0 ]]; then echo "Script failed with exit code $exit_code" >&2 fi}trap cleanup EXIT
# Error functionerror() { echo "ERROR: $*" >&2 return 1}
# Validate inputvalidate_input() { local file="$1" [[ -f "$file" ]] || error "File not found: $file" [[ -r "$file" ]] || error "File not readable: $file"}
# Retry logicretry() { 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"}
# Testvalidate_input "/etc/passwd" || exit 1retry curl -sf http://example.comInterview 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.”
Q49: How do you handle errors?
Section titled “Q49: How do you handle errors?”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 errorset -e
# Debug modeset -x
# Capture exit codecommandecho $?
# Trap errorstrap 'echo "Error on line $LINENO"' ERR
# Custom errorif [ ! -f "$file" ]; then echo "File not found" >&2 exit 1fiInterview 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.”
Cron and Scheduling
Section titled “Cron and Scheduling”Q50: How do you automate backups?
Section titled “Q50: How do you automate backups?”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.
# Cron jobcrontab -e# Add: 0 2 * * * /backup.sh
# /backup.sh#!/bin/bashtar -czpf /backup/$(date +%Y%m%d).tar.gz /datafind /backup -type f -mtime +30 -deleteInterview 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.”
Q51: How do you use cron jobs?
Section titled “Q51: How do you use cron jobs?”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.
# Edit crontabcrontab -e
# Examples# Run daily at 2am0 2 * * * /backup.sh
# Run every 5 minutes*/5 * * * * /monitor.sh
# Run on specific days0 0 * * 0 /weekly.sh
# System cron (runs even if user not logged in)/etc/cron.d/mycronInterview 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.”
Q52: How do you use cron?
Section titled “Q52: How do you use cron?”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.
# Edit crontabcrontab -e
# Examples# Every minute* * * * * /path/to/script.sh
# Daily at 2am0 2 * * * /path/to/script.sh
# Weekly on Sunday0 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.shInterview 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.”
Level 6: Package Management
Section titled “Level 6: Package Management”Debian/Ubuntu (apt, dpkg)
Section titled “Debian/Ubuntu (apt, dpkg)”Q53: How do you use apt?
Section titled “Q53: How do you use apt?”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.
# Updateapt updateapt upgrade
# Installapt install packageapt-get install package
# Removeapt remove packageapt autoremove
# Searchapt search package
# List installedapt list --installedInterview 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.”
RedHat/Fedora (dnf, yum, rpm)
Section titled “RedHat/Fedora (dnf, yum, rpm)”Q54: How do you use yum/dnf?
Section titled “Q54: How do you use yum/dnf?”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.
# Install packageyum install packagednf install package
# Updateyum updatednf update
# Searchyum search packagednf search package
# Removeyum remove packagednf autoremove
# List installedyum list installeddnf list installedInterview 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.”
SUSE (zypper)
Section titled “SUSE (zypper)”Q55: How do you use zypper?
Section titled “Q55: How do you use zypper?”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.
# Installzypper install package
# Updatezypper update
# Removezypper remove package
# Searchzypper search packageInterview 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.”
Repositories
Section titled “Repositories”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.
# Debian/Ubuntudeb http://archive.ubuntu.com/ubuntu/ jammy main restricted universe multiversedeb http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted universe multiverse
# Add repositoryadd-apt-repository ppa:nginx/stable
# Updateapt update
# RHEL/CentOS# /etc/yum.repos.d/*.repo[baseos]name=BaseOSbaseurl=https://dl.fedoraproject.org/pub/epel/$releasever/Everything/$basearchenabled=1
# Clean cacheapt cleanyum clean all
# List reposapt-cache policyyum repolistInterview 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.”
Q57: How do you manage repositories?
Section titled “Q57: How do you manage repositories?”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.
# yum add repoyum-config-manager --add-repo http://repo.example.com.repo
# apt add repoadd-apt-repository ppa:name/ppa# orecho "deb url" > /etc/apt/sources.list.d/file.listapt updateInterview 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.”
Install, Remove, and Upgrade
Section titled “Install, Remove, and Upgrade”Q58: How do you roll back updates?
Section titled “Q58: How do you roll back updates?”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.
# Debian/Ubuntu# Hold packageapt-mark hold apache2
# View installed versionsapt-cache policy nginx
# Downgradeapt install nginx=1.18.0-*
# Snapshots with aptapt install apt-cloneapt-clone clone myserver-packagesapt-clone restore myserver-packages.tar.gz
# RPM rollback (RHEL)# yum historyyum historyyum history undo <transaction-id>
# Transactional updates (openSUSE)transactional-updateInterview 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.”
Q59: How do you manage system updates?
Section titled “Q59: How do you manage system updates?”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.
# Debian/Ubuntuapt updateapt list --upgradableapt upgradeapt full-upgrade
# Unattended upgradesapt install unattended-upgrades# /etc/apt/apt.conf.d/50unattended-upgradesUnattended-Upgrade::Allowed-Origins { "${distro_id}:${distro_codename}-security";};
# RHEL/CentOSyum updateyum check-update
# Kernel live patching# Ubuntusnap install canonical-livepatchcanonical-livepatch enable <token>
# RHELyum install kpatchInterview 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.”
Build from Source
Section titled “Build from Source”Q60: How do you build from source?
Section titled “Q60: How do you build from source?”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.
# Download and extractwget urltar -xzvf file.tar.gz
# Configure./configure --prefix=/usr/local
# Buildmake
# Installmake install# orsudo make installInterview 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.”
Level 7: Boot Process and Systemd
Section titled “Level 7: Boot Process and Systemd”Boot Process Concepts
Section titled “Boot Process Concepts”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.
# View boot messagesdmesg | lessjournalctl -b
# Boot time analysissystemd-analyze timesystemd-analyze blame | head -20Interview 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.
# Edit GRUB configvim /etc/default/grub
# Common settingsGRUB_TIMEOUT=5GRUB_DEFAULT=savedGRUB_CMDLINE_LINUX="quiet splash"
# Regenerate configupdate-grub # Debian/Ubuntugrub2-mkconfig -o /boot/grub2/grub.cfg # RHEL/CentOS
# GRUB command line# Press 'e' at boot menu to editInterview 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.”
Q63: What is initramfs and its purpose?
Section titled “Q63: What is initramfs and its purpose?”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.
# Rebuild initramfsdracut -f # RHEL/CentOSupdate-initramfs -u # Debian/Ubuntu
# View contentslsinitramfs /boot/initrd.img-$(uname -r)zcat /boot/initrd.img | cpio -id
# Custom initramfs# Add to /etc/initramfs-tools/modulesInterview 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.”
Q64: How do you manage initramfs?
Section titled “Q64: How do you manage initramfs?”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.
# Update initramfsupdate-initramfs -u# ordracut -f
# List moduleslsinitramfs /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.”
Q65: How do you secure the boot process?
Section titled “Q65: How do you secure the boot process?”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.
# Enable UEFI secure boot# Sign kernel# 1. Generate keysopenssl req -new -x509 -newkey rsa:2048 -keyout MOK.priv -outform DER -out MOK.der -nodes -days 36500 -subj "/CN=My Secure Boot/"
# 2. Sign kernelsbsign --key MOK.priv --cert MOK.der /boot/vmlinuz-$(uname -r) --output /boot/vmlinuz-$(uname -r)
# 3. Enroll keymokutil --import MOK.der
# GRUB password protection# /etc/grub.d/40_customset superusers="admin"password_pbkdf2 admin grub.pbkdf2.sha512.10000.salt.hash
# Recompile GRUBupdate-grub
# Disable USB boot# BIOS settings or# /etc/modprobe.d/blacklist.confinstall usb-storage /bin/trueInterview talking point: “Machine Owner Keys (MOK) are enrolled locally to trust custom-signed kernels, ensuring boot integrity.”
Init Systems and systemd
Section titled “Init Systems and systemd”Q66: How does systemd replace SysVinit?
Section titled “Q66: How does systemd replace SysVinit?”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.
# Service unit example[Unit]Description=My ServiceAfter=network.target
[Service]Type=simpleExecStart=/usr/bin/myserviceRestart=on-failure
[Install]WantedBy=multi-user.target
# Manage servicesystemctl enable myservicesystemctl start myservicesystemctl status myserviceInterview 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.
# Systemd (modern)systemctl statussystemctl list-units --type=service
# SysVinit (legacy)runlevells -la /etc/rc.d/
# Runitsv 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 targetcat /etc/systemd/system/myapp.target[Unit]Description=My Application TargetRequires=network-online.targetAfter=network-online.target[Install]WantedBy=multi-user.targetInterview 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.”
Units and Service Files
Section titled “Units and Service Files”Q69: How do you create systemd service?
Section titled “Q69: How do you create systemd service?”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.
[Unit]Description=My ServiceAfter=network.target
[Service]Type=simpleUser=myuserGroup=mygroupWorkingDirectory=/opt/myappExecStart=/opt/myapp/bin/startExecStop=/opt/myapp/bin/stopExecReload=/bin/kill -HUP $MAINPIDRestart=on-failureRestartSec=10StandardOutput=journalStandardError=journal
[Install]WantedBy=multi-user.targetInterview 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.”
Q70: How do you use systemd tmpfiles?
Section titled “Q70: How do you use systemd tmpfiles?”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.
# Create directories with specific permissionsd /var/run/myservice 0755 myuser mygroup -L /var/run/myservice/link - - - - /var/myservice
# Runtimesystemd-tmpfiles --createsystemd-tmpfiles --clean
# At bootsystemctl enable systemd-tmpfiles-clean.timerInterview 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.”
Systemctl Management
Section titled “Systemctl Management”Q71: How do you manage services?
Section titled “Q71: How do you manage services?”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.
# SystemDsystemctl start servicesystemctl stop servicesystemctl restart servicesystemctl status servicesystemctl enable servicesystemctl disable service
# SysV initservice service_name startservice service_name stopInterview 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.”
Q72: How do you manage systemd services?
Section titled “Q72: How do you manage systemd services?”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.
# Start/stopsystemctl start nginxsystemctl stop nginxsystemctl restart nginx
# Enable/disable bootsystemctl enable nginxsystemctl disable nginx
# Statussystemctl status nginxsystemctl is-active nginx
# Listsystemctl list-units --type=servicesystemctl list-unit-files --type=serviceInterview 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.”
Q73: How do you debug systemd services?
Section titled “Q73: How do you debug systemd services?”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.
# Check statussystemctl status myservicejournalctl -u myservice
# Follow logsjournalctl -fu myservice
# Debug modesystemctl edit myservice# Add:# [Service]# Environment=SYSTEMD_LOG_LEVEL=debug
# Check dependenciessystemctl list-dependencies myservice
# Check failedsystemctl --failedsystemctl reset-failedInterview 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.”
Viewing Service Logs
Section titled “Viewing Service Logs”Q74: How do you use journalctl?
Section titled “Q74: How do you use journalctl?”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.
# View alljournalctl
# Sincejournalctl --since "1 hour ago"journalctl --since "2023-01-01"
# Untiljournalctl --until "2023-01-01"
# Priorityjournalctl -p err
# Servicejournalctl -u nginx
# Followjournalctl -f
# Disk usagejournalctl --disk-usageInterview 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.”
Q75: How do you use systemd journal?
Section titled “Q75: How do you use systemd journal?”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.
# View logsjournalctljournalctl -u nginx.servicejournalctl --since "1 hour ago"journalctl --since "2023-01-01"
# Priorityjournalctl -p err
# Followjournalctl -fInterview 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.”
Timers
Section titled “Timers”Q76: How do you create systemd timer?
Section titled “Q76: How do you create systemd timer?”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.
[Unit]Description=Run daily backup
[Timer]OnCalendar=dailyPersistent=trueRandomizedDelaySec=1h
[Install]WantedBy=timers.target
# /etc/systemd/system/mytimer.service[Unit]Description=Daily backup job
[Service]Type=oneshotExecStart=/usr/local/bin/backup.shInterview 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.”
Q77: How do you use systemd timers?
Section titled “Q77: How do you use systemd timers?”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.
[Unit]Description=Run daily at midnight
[Timer]OnCalendar=dailyPersistent=true
[Install]WantedBy=timers.target
# /etc/systemd/system/mytimer.service[Unit]Description=My Timer Job
[Service]Type=oneshotExecStart=/usr/local/bin/myscript.shInterview 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.”
Resource Limits and Sandboxing
Section titled “Resource Limits and Sandboxing”Q78: How do you limit systemd resources?
Section titled “Q78: How do you limit systemd resources?”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.
[Service]MemoryMax=1GMemoryHigh=512MCPUQuota=50%IOReadBandwidthMax=/dev/sda 1MIOWriteBandwidthMax=/dev/sda 1MTasksMax=100
# Applysystemctl daemon-reloadsystemctl restart myserviceInterview 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.”
Kernel Modules
Section titled “Kernel Modules”Q79: How do you load kernel modules?
Section titled “Q79: How do you load kernel modules?”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.
# List moduleslsmodmodinfo module_name
# Load modulemodprobe module_name
# Unload modulemodprobe -r module_name
# Module parametersmodprobe module_name parameter=value
# Persistent configuration# /etc/modprobe.d/blacklist.confblacklist module_name
# /etc/modprobe.d/module.confoptions module_name parameter=value
# Create module dependencydepmod -a
# View module infomodinfo -p module_nameInterview 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.
# Load module at bootloopst8021q
# Module parameters# /etc/modprobe.d/.confoptions bonding mode=active-backupoptions iptables conntrack_hashsize=262144
# Blacklist module# /etc/modprobe.d/blacklist.confblacklist nouveaublacklist snd_pcsp
# Create module dependenciesdepmod -a
# View loaded moduleslsmodInterview talking point: “Blacklisting prevents conflicting modules from loading, and depmod rebuilds dependencies after changing module configuration.”
Q81: How do you create kernel modules?
Section titled “Q81: How do you create kernel modules?”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.
#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");}# Makefileobj-m += hello.oKDIR := /lib/modules/$(shell uname -r)/buildall: make -C $(KDIR) M=$(PWD) modulesclean: make -C $(KDIR) M=$(PWD) clean
# Buildmake
# Loadinsmod hello.ko
# Unloadrmmod hello
# Checklsmod | grep hellodmesg | tailInterview 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.”
Q82: How do you manage kernel modules?
Section titled “Q82: How do you manage kernel modules?”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.
# List loadedlsmod
# Load modulemodprobe module_name
# Unload modulemodprobe -r module_name
# View module infomodinfo module_name
# Blacklistecho "blacklist module_name" >> /etc/modprobe.d/blacklist.confInterview 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.”
Boot Troubleshooting
Section titled “Boot Troubleshooting”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 filesystemmount -o remount,rw /
# Change passwordpasswd root
# RebootrebootInterview 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 mode1. Reboot system2. Press 'e' at GRUB menu3. Add 'single' or 'init=/bin/bash' to linux line4. Press Ctrl+X to boot5. mount -o remount,rw /6. passwd root7. exec /sbin/init
# Method 2: Using rescue disk1. Boot from rescue media2. Mount filesystem3. chroot /mnt/sysimage4. passwd root5. exit6. rebootInterview 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.”
Level 8: Storage
Section titled “Level 8: Storage”Disks and Partitions
Section titled “Disks and Partitions”Q85: How do you check disk health?
Section titled “Q85: How do you check disk health?”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.
# SMART statussmartctl -a /dev/sdasmartctl -H /dev/sda
# Disk usagedf -hdu -sh /*
# I/O statsiostat -x 1iotopInterview 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.”
Q86: How do you migrate LVM to new disk?
Section titled “Q86: How do you migrate LVM to new 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.
# Create new PVpvcreate /dev/sdc1
# Add to VGvgextend vg_name /dev/sdc1
# Move datapvmove /dev/sdb1 /dev/sdc1
# Remove oldvgreduce vg_name /dev/sdb1Interview 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.
# List partitionsfdisk -llsblkparted -l
# Create partitionfdisk /dev/sdb# n (new), p (primary), w (write)
# Formatmkfs.ext4 /dev/sdb1mkfs.xfs /dev/sdb1
# Mountmount /dev/sdb1 /mnt/dataInterview 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.”
Q88: How do you use dd?
Section titled “Q88: How do you use dd?”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.
# Clone diskdd if=/dev/sda of=/dev/sdb bs=4M status=progress
# Create imagedd if=/dev/sda of=/backup/sda.img bs=4M status=progress
# Restoredd if=/backup/sda.img of=/dev/sda bs=4M status=progress
# Zero diskdd if=/dev/zero of=/dev/sda bs=1M status=progress
# Test speeddd if=/dev/zero of=/tmp/test bs=1G count=1 oflag=directInterview 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.
# Create LUKScryptsetup luksFormat /dev/sdb1
# Opencryptsetup open /dev/sdb1 crypt_vol
# Formatmkfs.ext4 /dev/mapper/crypt_vol
# Mountmount /dev/mapper/crypt_vol /mnt/data
# Closeumount /mnt/datacryptsetup close crypt_vol
# Auto mount# /etc/crypttabcrypt_vol /dev/sdb1 none luksInterview 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.”
Q90: How do you encrypt partitions?
Section titled “Q90: How do you encrypt partitions?”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.
# LUKS encryptioncryptsetup luksFormat /dev/sdb1cryptsetup luksOpen /dev/sdb1 crypt_volmkfs.ext4 /dev/mapper/crypt_volmount /dev/mapper/crypt_vol /mnt/data
# Closeumount /mnt/datacryptsetup luksClose crypt_volInterview 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.”
Filesystems
Section titled “Filesystems”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.
# Create ext4mkfs.ext4 -j /dev/sdb1
# Create XFSmkfs.xfs -f /dev/sdb1
# Tune ext4tune2fs -o journal_data /dev/sda1tune2fs -O dir_index /dev/sda1Interview 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.”
Q92: How do you configure zfs dedup?
Section titled “Q92: How do you configure zfs dedup?”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.
# Enable dedupzfs set dedup=on pool1/data
# Check dedup ratiozpool status -D pool1
# With specific algorithmzfs set dedup=sha256,verify pool1/dataInterview 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.
# Create ext4mkfs.ext4 /dev/sdb1
# With optionsmkfs.ext4 -T largefile -m 0 /dev/sdb1
# Tunetune2fs -c 30 /dev/sdb1 # check every 30 mountstune2fs -i 30d /dev/sdb1 # check every 30 days
# Checke2fsck -f /dev/sdb1
# Resizeresize2fs /dev/sdb1 # to fill partitionresize2fs /dev/sdb1 10G # shrink to 10GInterview 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.”
Q94: How do you create btrfs filesystem?
Section titled “Q94: How do you create btrfs filesystem?”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.
# Createmkfs.btrfs -L mydata /dev/sdb
# RAID levelsmkfs.btrfs -d raid1 -m raid1 /dev/sdb /dev/sdc
# Subvolumesmount /dev/sdb /mnt/btrfsbtrfs subvolume create /mnt/btrfs/vol1
# Snapshotsbtrfs subvolume snapshot /mnt/btrfs/vol1 /mnt/btrfs/snap1
# Propertiesbtrfs property set /mnt/btrfs/vol1 compression zstdInterview 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.”
Q95: How do you create XFS filesystem?
Section titled “Q95: How do you create XFS filesystem?”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.
# Create XFSmkfs.xfs /dev/sdb1
# With optionsmkfs.xfs -f -d agcount=4 -l size=100m /dev/sdb1
# Checkxfs_repair /dev/sdb1
# Growxfs_growfs /mount/point
# Repairxfs_repair -n /dev/sdb1 # just checkInterview 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.”
Q96: How do you use btrfs balance?
Section titled “Q96: How do you use btrfs balance?”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.
# Full balancebtrfs balance start /mnt/btrfs
# Specific profilebtrfs balance start -dconvert=raid1 -mconvert=raid1 /mnt/btrfs
# With filtersbtrfs balance start -dusage=50 /mnt/btrfs
# Statusbtrfs balance status /mnt/btrfsInterview 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.”
Q97: How do you use btrfs raid1?
Section titled “Q97: How do you use btrfs raid1?”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.
# Convert to RAID1btrfs balance start -dconvert=raid1 -mconvert=raid1 /mnt/btrfs
# Add devicebtrfs device add /dev/sdc1 /mnt/btrfs
# Remove devicebtrfs device remove /dev/sdb1 /mnt/btrfsInterview 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.”
Q98: How do you use btrfs send/receive?
Section titled “Q98: How do you use btrfs send/receive?”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.
# Initial backupbtrfs send /mnt/snap1 | gzip > backup1.gz
# Incrementalbtrfs send -p /mnt/snap1 /mnt/snap2 | gzip > backup2.gz
# Receivegzip -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.”
Q99: How do you use btrfs?
Section titled “Q99: How do you use btrfs?”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.
# Create btrfsmkfs.btrfs -L mydata /dev/sdb
# Mountmount /dev/sdb /mnt/btrfs
# Subvolumesbtrfs subvolume create /mnt/btrfs/databtrfs subvolume list /mnt/btrfs
# Snapshotsbtrfs subvolume snapshot /mnt/btrfs/data /mnt/btrfs/snap
# Balancebtrfs balance start /mnt/btrfs
# Compressionmount -o compress=zstd /dev/sdb /mnt/btrfs
# RAIDmkfs.btrfs -d raid1 -m raid1 /dev/sdb /dev/sdcInterview 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.”
Q100: How do you use zfs send/receive?
Section titled “Q100: How do you use zfs send/receive?”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.
# Full sendzfs send pool1/data@snap1 | ssh host "zfs receive pool1/data"
# Incrementalzfs send -i pool1/data@snap1 pool1/data@snap2 | ssh host "zfs receive pool1/data"
# Compressedzfs 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.”