Bash Scripting Interview Questions and Labs
# CHAPTER 19
Bash Scripting Interview Questions and Labs
1. Introduction
Reading a tutorial provides knowledge, but technical interviews test execution under pressure. When interviewing for a DevOps Engineer, Site Reliability Engineer (SRE), or Systems Administrator role, you will be expected to rapidly decipher broken code, articulate complex execution flows, and synthesize multiple concepts (loops, conditions, text processing) into immediate solutions. In this chapter, we have curated high-impact, real-world technical interview questions and scenario-based troubleshooting labs. These exercises are designed to forge your theoretical Bash knowledge into the practical, rapid-fire operational skills demanded by senior hiring managers.2. Learning Objectives
By the end of this chapter, you will be able to:- Confidently articulate solutions to complex Bash scripting interview questions.
- Identify and verbally debug syntax errors in provided script examples.
- Synthesize arrays, loops, and conditional logic into on-the-spot automation solutions.
-
Demonstrate a robust understanding of execution environments (
cron,$PATH).
- Execute rapid-fire command combinations using pipes and filters.
3. Core Technical Interview Questions
Q1: "Walk me through the mechanical difference between $* and $@ when processing command-line arguments in Bash."
*How to answer (The Gold Standard):* "Both variables hold all the arguments passed to the script. However, the critical difference occurs when they are wrapped in double quotes. "$*" takes all the arguments and merges them into a single, massive string. "$@" preserves the arguments as a true array of separate, distinct words. In almost every DevOps for loop scenario, "$@" is the correct and secure choice to prevent variables from fusing together."
Q2: "You write a backup script and schedule it in your personal crontab -e. The script runs the command docker restart web. It works perfectly when you run it manually, but cron silently fails every night. What are the two most likely causes?"
*How to answer:* "First, the Cron Environment Trap. Cron does not load the user's .bashrc, so the $PATH is severely restricted. The script likely cannot find the docker executable. I must update the script to use the absolute path, such as /usr/bin/docker. Second, permissions. The docker command requires root elevation. If the script is in my personal user crontab instead of the root crontab (sudo crontab -e), it will fail due to lack of privileges."
Q3: "Explain the purpose and execution behavior of the directive set -e."
*How to answer:* "set -e enables Bash Strict Mode. By default, if a command in a Bash script fails, the interpreter ignores the error and executes the very next line of code, which can cause catastrophic, cascading failures. set -e forces the script to immediately abort execution the instant any command returns a non-zero exit status, ensuring fail-fast reliability in deployment pipelines."
4. Code Debugging Labs (Find the Bug)
Interviewers will often hand you a printed piece of code or share their screen and ask you to spot the error.Lab 1: The Broken If Statement *The Code:*
*The Error:* There are two critical bugs.
-
1.
Missing spaces: Bash requires spaces inside the test brackets:
[ $USER_COUNT == 5 ].
-
2.
Wrong operator: Because
USER_COUNTis an integer, the numeric comparison operator-eqshould be used instead of the string operator==.
Lab 2: The Infinite Loop *The Code:*
*The Error:* The COUNTER variable is never incremented inside the do block. The condition 1 <= 10 will remain true forever, resulting in a CPU-locking infinite loop. The fix is injecting let COUNTER++ before the done statement.
Lab 3: The Dangerous Variable *The Code:*
*The Error:* Lack of validation and unquoted variables. If the user executes the script without providing an argument, $TARGET_DIR evaluates to blank. The command resolves to rm -rf /*, deleting the entire Linux operating system. The fix is wrapping the variable in quotes ("$TARGET_DIR"/*) and adding an if [ -z "$1" ] validation check at the top.
5. Rapid-Fire Terminal Challenges
You are given a terminal and asked to achieve a result using one-liners.Challenge 1: Log Extraction
*Task:* You have a file named access.log. Print only the lines containing the word "ERROR", but do not display the word "ERROR" itself; only print the 3rd column of those lines.
*Solution:* grep "ERROR" access.log | awk '{print $3}'
Challenge 2: Process Termination
*Task:* Find the Process ID (PID) of a script named rogue_task.sh and forcefully terminate it.
*Solution:* ps aux | grep "rogue_task.sh". (Note the PID, e.g., 1045). Then kill -9 1045.
Challenge 3: Mass Renaming
*Task:* Write a single-line for loop directly in the terminal to append the word .bak to every .txt file in your current directory.
*Solution:* for FILE in *.txt; do mv "$FILE" "$FILE.bak"; done
6. Preparing for the Technical Assessment
When an interviewer presents a scenario, remember these rules:-
1.
Never assume the environment: Always state that you would verify file permissions (
chmod +x), paths ($PATH), and dependencies before writing complex logic.
-
2.
Prioritize Safety: If asked to write a destructive script (like a cleanup tool), explicitly state you would use
set -e, quote all variables, and execute dry runs (echo rm...) before executing live deletions.
-
3.
Keep it simple: Interviewers prefer a clean, readable 10-line script using basic tools over an unreadable 1-line cryptographic
awk/sedwizardry command. Readability is paramount in team environments.
7. Summary
In Chapter 19, we stress-tested your foundational Bash knowledge against the rigor of a professional technical interview. We practiced articulating the nuanced mechanics of arrays ($@), strict environments (set -e), and cron limitations. We forensically analyzed broken code blocks, identifying catastrophic syntax errors, infinite loops, and severe command injection vulnerabilities. Finally, we executed rapid-fire, chained command workflows, proving that you possess the agility to translate complex operational requirements into immediate, functional terminal logic.