Page Content

Tutorials

Scenario Based Shell Scripting Interview Questions For Linux

This blog discusses scenario based shell scripting interview questions as well as exam topics and interview questions.

Shell scripting Interview Questions and Exam Topics

Shell scripting continues to be a fundamental component in technical interviews and DevOps certification tests. Employers want to see that you can handle edge circumstances, optimize for speed, and select the appropriate tool for the particular infrastructure work at hand, not just that you can build a loop.

Mastery of Common Shell Commands

Interviewers frequently begin with the Linux tools. In addition to outlining their roles, explain how to combine them to solve problems.

  • Text Processing: grep (searching), sed (stream editing), and awk (column manipulation).
  • System Discovery: find (locating files by metadata), lsof (list open files), and netstat/ss (network statistics).
  • Data Handling: jq (essential for parsing JSON output from Cloud CLIs) and sort/uniq (for data deduplication).

Also Read About Loops In Shell Scripting For Automation And Task Management

Script Debugging Strategies

One typical exam situation is a script that is “failing silently.” You must show that you can fix it in a methodical way.

  • The Verbose Mode: Using set -x to trace execution and set -v to read lines as they are processed.
  • The Unofficial Strict Mode: Explaining why set -euo pipefail is the gold standard for production scripts.
  • Static Analysis: Bringing up programs like ShellCheck, which may detect syntax mistakes and improper behavior automatically.

Scenario-Based Scripting

You are given a problem and asked to write a solution on your whiteboard in these questions.

  • Log Parsing: Using an access log, write a one-liner to identify the top five IP addresses that are contacting your Nginx server.
  • System Health: Write a script that, in the event that a service is not present in the process list, restarts it.
  • File Management: Locate and compress every log in /var/log that is more than 100MB in size and more than three days old.

Performance Optimization

Ineffective scripts become bottlenecks as data volumes increase. “Process-aware” coding is what interviewers search for.

  • Reducing Forks: Steer clear of superfluous subshells. Use a grep pattern file in instead of cat file | grep pattern.
  • Parallelization: Using & with wait or GNU Parallel to run tasks across multiple CPU cores.
  • Built-ins vs Externals: Understanding that shell built-ins (like [[ ]]) are faster than external binaries (like test or [ ]) because they don’t require spawning a new process.

Shell vs Python: When to Use Which?

This is a classic “architectural” question. There is no single right answer, but there is a right logic.

FeatureShell Scripting (Bash)Python
System IntegrationExcellent; direct access to OS tools.Requires os or subprocess modules.
Speed of DevelopmentFaster for simple wrappers and pipes.Slower to setup (imports, environments).
ReadabilityBecomes “write-only” code if too long.Highly readable and maintainable.
Data StructuresLimited (Arrays, Strings).Rich (Dictionaries, Lists, Objects).
Error HandlingBasic (Exit codes, Traps).Robust (Try/Except blocks).

The DevOps Rule of Thumb: Using Shell for “glue” operations under 100 lines (backups, small deployments) is the DevOps Rule of Thumb. If you need to work with complicated APIs, manipulate massive amounts of data, or have a script that needs to be maintained over many years by a large team, use Python.

Key Exam Checklist

  1. Can you explain the difference between hard links and soft links?
  2. Do you know how to use trap to clean up temporary files on script failure?
  3. Can you explain how SSH keys and agent forwarding work within a script?

Scenario based shell scripting interview questions

Scenario based shell scripting interview questions
Scenario based shell scripting

The purpose of scenario-based questions is to assess your capacity to apply reasoning to actual infrastructure issues. The interviewer wants to see how you think, not just how well you can memorise instructions, in a DevOps or System Admin interview.

The “Health Check” Scenario

Scenario: “You have 50 servers. Write a script that pings each server from a list in servers.txt and reports which ones are down.”

Solution Strategy: Use a for loop to iterate through the file and an if statement to check the exit status of the ping command.

#!/bin/bash
SERVER_FILE="servers.txt"

for server in $(cat $SERVER_FILE); do
    # -c 1 sends one packet, -W 1 sets a 1-second timeout
    ping -c 1 -W 1 "$server" > /dev/null 2>&1
    
    if [ $? -eq 0 ]; then
        echo "Server $server is UP"
    else
        echo "Server $server is DOWN" >> down_servers.log
    fi
done

Handling exit codes ($?) to determine command success.

Also Read About Most Commanly Asked Shell Scripting Examples For Interview

The “Log Rotation” Scenario

Scenario: “Your application log file /var/log/app.log is growing too large. Write a script to archive it if it exceeds 100MB and create a new empty log file.”

Solution Strategy: Use stat or du to check file size and mv to rotate.

#!/bin/bash
LOG_FILE="/var/log/app.log"
MAX_SIZE=104857600 # 100MB in bytes

FILE_SIZE=$(stat -c%s "$LOG_FILE")

if [ "$FILE_SIZE" -gt "$MAX_SIZE" ]; then
    TIMESTAMP=$(date +%Y%m%d%H%M)
    mv "$LOG_FILE" "$LOG_FILE.$TIMESTAMP.bak"
    touch "$LOG_FILE"
    chmod 644 "$LOG_FILE"
    echo "Log rotated at $TIMESTAMP"
fi

File attribute checking and timestamping.

The “Process Monitor” Scenario

Scenario: “The nginx service occasionally crashes. Write a script that checks if the process is running every 5 minutes and restarts it if it’s down.”

Solution Strategy: Use pgrep or systemctl for process checking.

#!/bin/bash
SERVICE="nginx"

if ! pgrep -x "$SERVICE" > /dev/null; then
    echo "$(date): $SERVICE is down. Restarting..." >> /var/log/service_monitor.log
    systemctl start "$SERVICE"
fi

Using cron jobs (*/5 * * * *) in conjunction with the script for persistent monitoring.

The “Data Extraction” Scenario

Scenario: “A CSV file users.csv has columns: Name,Email,Department. Write a script to extract only the emails of people in the ‘IT’ department.”

Solution Strategy: This is a classic awk or grep problem.

#!/bin/bash
# Using awk: -F',' sets the delimiter to comma
# If column 3 is "IT", print column 2
awk -F',' '$3 == "IT" {print $2}' users.csv

Stream editing and field manipulation.

Scenarios types

Scenario TypePrimary ToolsPro Tip
Parsing Logsgrep, awk, sedUse tail -f for real-time monitoring.
Disk/Resourcedf, du, topAlways use -h for human-readable output.
Permission Issueschmod, chown, statMention “Recursive” -R if handling directories.
API/Webcurl, wget, jqjq is essential for parsing JSON responses.

Also Read About Shell Script Compiler SHC: Features, Usage, And Examples

Hemavathi
Hemavathihttps://govindhtech.com/
Myself Hemavathi graduated in 2018, working as Content writer at Govindtech Solutions. Passionate at Tech News & latest technologies. Desire to improve skills in Tech writing.
Index