Skip to main content
Shell Scripting – Complete Beginner to Advanced Guide
CHAPTER 19 Intermediate

Shell Scripting Interview Questions and Labs

Updated: May 16, 2026
30 min read

# CHAPTER 19

Shell Scripting Interview Questions and Labs

1. Introduction

Reading a tutorial provides knowledge, but technical interviews demand the execution of that knowledge under extreme pressure. When interviewing for a DevOps Engineer, Site Reliability Engineer (SRE), or Unix 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, functional solutions. In this chapter, we have curated high-impact, real-world technical interview questions and scenario-based troubleshooting labs. These exercises are meticulously designed to forge your theoretical shell scripting 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 verbal solutions to complex shell scripting interview questions.
  • Identify and verbally debug catastrophic syntax errors in provided script examples.
  • Synthesize arrays, loops, and conditional logic into on-the-spot automation solutions.
  • Demonstrate a robust understanding of Unix execution environments (cron, $PATH).
  • Execute rapid-fire command combinations using pipelines (|) and filters.

3. Core Technical Interview Questions

Q1: "Walk me through the mechanical difference between $* and $@ when processing command-line arguments in a shell script." *How to answer (The Gold Standard):* "Both variables capture all the arguments passed to the script. However, the critical architectural difference occurs when they are wrapped in double quotes. "$*" takes all the arguments and merges them into a single, massive continuous 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 distinct 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 interactively, but cron silently fails every single night. What are the two most likely causes?" *How to answer:* "First, the Cron Environment Trap. Cron does not load the user's interactive .profile, so the $PATH is severely restricted. The script likely cannot find the docker executable. I must update the script to utilize the absolute path, such as /usr/bin/docker. Second, permissions. The docker command requires root elevation. If the script is scheduled in my personal user crontab instead of the root crontab (sudo crontab -e), it will fail due to a lack of privileges."

Q3: "Explain the purpose and execution behavior of the directive set -e." *How to answer:* "set -e enables Strict Execution Mode. By default, if a command in a shell script fails, the interpreter ignores the error and boldly executes the very next line of code, which can cause catastrophic, cascading failures (like changing to a missing directory and then deleting files). 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 frequently 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:*

sh
12345
#!/bin/sh
USER_COUNT=5
if [$USER_COUNT = 5]; then
    echo "Max capacity reached."
fi

*The Error:* There are two critical bugs.

  1. 1. Missing spaces: The shell strictly requires blank spaces inside the test brackets: [ $USERCOUNT = 5 ].
  1. 2. Wrong operator: Because USERCOUNT is a numeric integer, the numeric comparison operator -eq should be utilized instead of the string operator =.

Lab 2: The Infinite Loop *The Code:*

sh
123456
#!/bin/sh
COUNTER=1
while [ $COUNTER -le 10 ]
do
    echo "Executing pass $COUNTER"
done

*The Error:* The COUNTER variable is never mathematically incremented inside the do block. The condition 1 <= 10 will remain true forever, resulting in a CPU-locking infinite loop. The fix is injecting an arithmetic increment expression (like COUNTER=$(expr $COUNTER + 1)) before the done statement.

Lab 3: The Dangerous Variable *The Code:*

sh
123
#!/bin/sh
TARGET_DIR=$1
rm -rf $TARGET_DIR/*

*The Error:* Lack of validation and unquoted variables. If the user executes the script without providing an argument, $TARGETDIR evaluates to blank. The command resolves to rm -rf /*, violently deleting the entire Linux operating system. The fix requires wrapping the variable in quotes ("$TARGETDIR"/*) and adding an if [ -z "$1" ] validation check at the top of the file to guarantee data exists.

5. Rapid-Fire Terminal Challenges

You are provided a terminal and asked to achieve a specific result utilizing one-liners.

Challenge 1: Log Extraction *Task:* You have a massive 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 runaway script named roguetask.sh and forcefully terminate it. *Solution:* ps aux | grep "roguetask.sh". (Note the PID from the second column, e.g., 1045). Then execute 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 working directory. *Solution:* for FILE in *.txt; do mv "$FILE" "${FILE}.bak"; done

6. Preparing for the Technical Assessment

When an interviewer presents an abstract scenario, remember these three golden rules:
  1. 1. Never assume the environment is perfect: Always state out loud that you would verify file permissions (chmod +x), paths ($PATH), and dependencies before writing complex logic.
  1. 2. Prioritize Safety over Speed: If asked to write a destructive script (like a cleanup tool), explicitly state you would utilize set -e, double-quote all variables, and execute dry runs (echo rm...) before executing live deletions.
  1. 3. Keep it readable: Interviewers prefer a clean, readable 10-line script utilizing basic, understandable tools over an unreadable 1-line cryptographic awk/sed wizardry command. Readability is paramount in collaborative team environments.

7. Summary

In Chapter 19, we stress-tested your foundational Shell scripting knowledge against the intense rigor of a professional technical interview. We practiced articulating the nuanced mechanics of arrays ($@), strict environments (set -e), and cron isolation 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.

8. Next Chapter Recommendation

You have survived the interview process. Now, you must prove your worth on the job by architecting a full-scale automation suite. Proceed to the Final Capstone: Chapter 20: Build Real-World Shell Automation Projects.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·