ThisCalculator

Everyday

Shell Scripting Interview Questions & Answers

Updated · Standard formula, shown below

This article answers the most common interview questions about shell scripting, covering everything from basic syntax to debugging and real-world problem solving. You’ll learn what interviewers typically ask, what they’re really testing, and how to structure strong, concise answers that demonstrate practical experience.

Why Interviewers Ask About Shell Scripting

Shell scripting is a core skill for DevOps engineers, system administrators, and backend developers working in Linux/Unix environments. Interviewers ask about it to gauge your ability to automate repetitive tasks, manipulate text, manage processes, and navigate the command line efficiently. They want to see that you understand not just the syntax, but also the philosophy of composing small tools that work together. A candidate who can write a robust, readable script that handles errors gracefully is far more valuable than one who only memorizes commands.

Core Concepts You Must Know

Before diving into specific questions, you should be comfortable with these foundational topics that form the basis of most interview questions:

  • Shebang line: #!/bin/bash or #!/bin/sh – tells the system which interpreter to use.
  • Variables and expansion: $var, ${var}, command substitution $(cmd), and arithmetic expansion $((...)).
  • Exit codes: Every command returns a number (0 for success, non-zero for failure). Check with $?.
  • Conditionals: if, elif, else, and test constructs like [ ... ] or [[ ... ]].
  • Loops: for, while, until, and how to iterate over files or command output.
  • Functions: Define with function_name() { ... } and call without parentheses.
  • Input handling: $1, $2, $@, $#, and reading from stdin with read.
  • Text processing: grep, sed, awk, and cut – these are the bread and butter of shell scripting.

Common Interview Questions and How to Answer Them

Here are the questions that appear most frequently, with a breakdown of what the interviewer is looking for:

1. What is the difference between bash and sh?

sh (the Bourne shell) is the original Unix shell, while bash (Bourne Again Shell) is a superset that adds features like arrays, arithmetic expansion, and improved pattern matching. Many systems symlink /bin/sh to bash or dash for speed. A good answer mentions that scripts using #!/bin/sh should stick to POSIX syntax for portability, while #!/bin/bash allows more advanced features.

2. How do you debug a shell script?

Mention running the script with bash -x script.sh to trace each command, or adding set -x inside the script to enable tracing. Also mention set -e to exit on error, set -u to treat unset variables as errors, and set -o pipefail to catch failures in pipelines. These options are often combined at the top of a script: set -euo pipefail.

3. What is the difference between $@ and $*?

Both represent all positional parameters, but $@ treats each argument as a separate word, which is safer when arguments contain spaces. $* joins all arguments into a single string. In practice, always use "$@" to preserve argument boundaries.

4. How do you find and kill a process by name?

You can use pgrep to find the PID(s) and pkill to kill them. For example: pkill -f "process_name". Alternatively, combine ps aux | grep process_name | awk '{print $2}' | xargs kill. A better answer explains why pkill is preferred and mentions the -f flag to match the full command line.

5. How do you read a file line by line?

The classic idiom is while IFS= read -r line; do echo "$line"; done < file.txt. The -r prevents backslash escapes, and IFS= preserves leading/trailing whitespace. This is a common question because many beginners use a for loop, which splits on whitespace and fails for lines with spaces.

6. What is a zombie process and how do you handle it?

A zombie is a process that has finished but still has an entry in the process table because its parent hasn't called wait(). You can't kill a zombie with kill; you need to kill the parent or have the parent reap it. Explain that this is normal for short-lived children and only becomes a problem when many accumulate.

Hands-On Tasks Interviewers Often Give

Many interviews include a live coding exercise. You might be asked to write a script that:

  • Checks if a file exists and is readable.
  • Parses a CSV or log file and extracts specific fields.
  • Renames a batch of files based on a pattern.
  • Monitors disk usage and sends an alert if above a threshold.
  • Backs up a directory and rotates old backups.

Practice these scenarios. When solving, show your thought process: start with the simplest approach, then add error handling and edge cases. For example, a backup script should check if the source directory exists, create the destination if needed, and verify the backup was created successfully.

Common Mistakes to Avoid in Your Answers

Interviewers often look for awareness of these pitfalls:

  • Not quoting variables: Always quote "$var" unless you intentionally want word splitting.
  • Using cat unnecessarily: cat file | grep pattern is a useless use of cat; use grep pattern file directly.
  • Forgetting exit codes: Always check if a command succeeded before proceeding, especially in critical scripts.
  • Parsing ls output: It's fragile; use globbing or find instead.
  • Ignoring whitespace: When iterating over files, use find -print0 and xargs -0 to handle filenames with spaces.

How to Prepare for a Shell Scripting Interview

Beyond memorizing syntax, you should be able to explain the rationale behind your choices. Review the man pages for common commands, practice writing small scripts from scratch, and understand how pipelines and redirection work. Also, be ready to discuss a script you wrote in a previous job: what problem it solved, how you handled errors, and how you tested it. Interviewers value candidates who can think about maintainability and portability.

Frequently Asked Questions

What's the difference between single and double quotes in shell?

Single quotes preserve the literal value of every character inside them; no expansion occurs. Double quotes allow variable expansion and command substitution, but still prevent word splitting and globbing. For example, echo "$HOME" prints your home directory, while echo '$HOME' prints $HOME.

How do I pass arguments to a shell script?

Arguments are accessed via $1, $2, etc., $0 is the script name, $# is the number of arguments, and "$@" expands to all arguments as separate words. You can also use shift to discard the first argument and move the rest down.

What is the purpose of set -e in a script?

set -e causes the script to exit immediately if any command returns a non-zero exit status. This is useful for catching errors early, but it can be tricky because commands in conditionals or pipelines may behave unexpectedly. Combine with set -o pipefail to catch failures in the middle of a pipeline.

How do I check if a string contains a substring in bash?

Use the [[ $string == *substring* ]] pattern, or use case for POSIX-compatible scripts. For example: if [[ "$str" == *"needle"* ]]; then echo "found"; fi. Another way is to use grep -q if you're working with text streams.

What is the difference between source and executing a script?

source script.sh (or . script.sh) runs the script in the current shell context, so any variables or functions defined become available in the current session. Executing ./script.sh runs it in a subshell, so changes are not persisted. Use source when you want to load configuration or define functions.

How do I loop over files in a directory?

The safest way is to use a glob: for file in /path/*.txt; do echo "$file"; done. This handles filenames with spaces correctly. For recursive searches, use find with -exec or a while read loop with find ... -print0.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.