Skip to main content
Cloud, DevOps & Systems

Bash Scripting Interview Questions

All Levels (Junior to Staff)16 Questions

Shell scripting technical guide: POSIX compliance, parameter expansion, subshell execution, piping backpressure, trap signal handling, and robust script debugging.

18 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice Bash Scripting Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

Why should almost every variable expansion in Bash be double-quoted ("$var"), and how do "$@" and "$*" differ?

Senior Engineering Answer

Unquoted expansions undergo Word Splitting (splitting on $IFS characters like spaces and tabs) and Pathname Expansion (globbing characters like * or ?). Quoting "$var" suppresses both so filenames with spaces or globs stay intact as a single argument. For positional parameters, "$@" expands each argument as a separate quoted word (preserving spaces inside individual args), whereas "$*" joins all arguments into a single string separated by the first character of IFS.

Production Code Example
backup_files() {
  local dest="$1"
  shift
  # Preserves spaces in filenames passed as separate args
  cp -- "$@" "$dest/"
}
Common Interview Trap / Anti-Pattern:

Using $@ without double quotes behaves just like unquoted $*, silently breaking filenames containing spaces.

Question #2FundamentalJunior

What is the difference between [ ] (test), [[ ]] (extended test), and (( )) (arithmetic evaluation) in Bash?

Senior Engineering Answer

[ ] is a POSIX command (alias for test) where word splitting and globbing apply to unquoted arguments and > is treated as output redirection unless escaped. [[ ]] is a Bash keyword that disables word splitting/globbing on variables, supports && / ||, pattern matching (== *.log), and regex matching (=~). (( )) evaluates C-style integer arithmetic directly without $ prefixes and returns exit code 0 when the result is non-zero.

Production Code Example
name="deploy prod.log"
if [[ -f $name && $name == *.log ]]; then
  count=5
  if (( count > 3 )); then
    printf 'Found %d logs\n' "$count"
  fi
fi
Common Interview Trap / Anti-Pattern:

In [[ $str =~ $regex ]], putting quotes around $regex forces literal string matching instead of regex matching—store the pattern in a variable and leave it unquoted on the right-hand side of =~.

Question #3FundamentalJunior

What does set -euo pipefail do, and why is it called unofficial Bash strict mode?

Senior Engineering Answer

set -e (errexit) exits the script when an unchecked simple command returns a non-zero exit code. set -u (nounset) treats referencing an unset variable as a fatal error, catching typos like $TEMP_DRI before running rm -rf "$TEMP_DRI/*". set -o pipefail makes a pipeline return the exit status of the rightmost command that failed rather than masking errors with a trailing grep or tee that succeeded.

Production Code Example
#!/usr/bin/env bash
set -euo pipefail

# Pipeline fails properly if curl fails instead of tee returning 0
curl -fsSL "https://example.com/data.json" | jq '.items[]'
Common Interview Trap / Anti-Pattern:

Do not assume set -e catches everything: commands inside if conditions, || / && lists, and subshells inside local var=$(cmd) bypass errexit.

Question #4FundamentalJunior

How do Bash parameter expansions like ${var:-default}, ${var:?msg}, ${var##*/}, and ${var%/*} eliminate external sed/awk calls?

Senior Engineering Answer

Parameter expansion executes inside the Bash process with zero fork/exec overhead. ${var:-default} falls back if var is unset or empty; ${var:?error} aborts with a message if missing; ${path##*/} strips the longest prefix matching */ (fast basename); ${path%/*} strips the shortest suffix matching /* (dirname); and ${str//old/new} replaces all occurrences globally.

Production Code Example
env="${DEPLOY_ENV:-staging}"
api_key="${API_KEY:?API_KEY must be set}"

filepath="/var/log/app/service.log"
filename="${filepath##*/}"   # service.log
dirname="${filepath%/*}"     # /var/log/app
Common Interview Trap / Anti-Pattern:

Confusing :- (unset OR empty) with - (only unset), and forgetting that ${var:-default} does not assign the default back to var—use ${var:=default} for assignment.

Question #5IntermediateMid-Level

Why does a pipeline like cmd | while read -r line; do count=$((count+1)); done lose updates to count, and how do you fix it?

Senior Engineering Answer

By default in Bash, each stage of a pipeline runs in a separate subshell process. Variable mutations inside the while loop modify the subshell's copy of memory and disappear as soon as the pipeline finishes. Fix this by feeding the loop via Process Substitution (< <(cmd)) or a Here-String (<<<), or by enabling shopt -s lastpipe (only effective when job control is disabled, as in non-interactive scripts).

Production Code Example
count=0
while IFS= read -r line; do
  ((++count))
done < <(printf 'a\nb\nc\n')

printf 'Total lines: %d\n' "$count" # Prints 3
Common Interview Trap / Anti-Pattern:

When using arithmetic under set -e, ((count++)) returns exit code 1 when count starts at 0 (post-increment evaluates to 0, which is falsy) and aborts the script! Use ((++count)) or count=$((count + 1)).

Question #6IntermediateMid-Level

How do you safely iterate over arbitrary filenames (including spaces, newlines, and leading hyphens) in Bash without breaking on word splitting?

Senior Engineering Answer

Never parse ls output (for f in $(ls))—it breaks on spaces, globs, and newlines. For simple directory matches, use shell globbing with nullglob; for recursive searches, pair find -print0 with while IFS= read -r -d '' file. Always pass -- before filenames to tools like rm, mv, or grep so filenames starting with '-' (e.g., -rf) are not parsed as flags.

Production Code Example
while IFS= read -r -d '' file; do
  printf 'Processing: %q\n' "$file"
  chmod 0644 -- "$file"
done < <(find /var/uploads -type f -name '*.txt' -print0)
Common Interview Trap / Anti-Pattern:

Omitting IFS= causes read to trim leading and trailing whitespace from filenames; omitting -r causes read to interpret backslashes as escape characters.

Question #7IntermediateMid-Level

How does process substitution (<(command) and >(command)) work under the hood, and when does it fail?

Senior Engineering Answer

Process substitution spawns the inner command asynchronously and connects its stdout (for <()) or stdin (for >()) to a named pipe (FIFO) or /dev/fd/N file descriptor, passing that path as a filename argument to the outer command. It lets tools expecting file paths (like diff <(sort a) <(sort b) or comm) consume streams without temporary files. It fails when programs need seekable files (lseek), check file size via stat, or close inherited file descriptors beyond 0/1/2 (e.g., sudo or certain privileged binaries).

Production Code Example
# Compare sorted outputs without temp files
diff -u <(sort -u hosts_a.txt) <(sort -u hosts_b.txt)

# Tee stdout to both console and a gzipped log stream
exec > >(tee >(gzip -c > run.log.gz)) 2>&1
Common Interview Trap / Anti-Pattern:

Because >(cmd) runs asynchronously, the main script may exit before the consumer inside >() finishes flushing output unless you wait for background descriptors or close exec redirections explicitly.

Question #8IntermediateMid-Level

How do trap handlers and mktemp ensure atomic temporary file and lock cleanup in Bash scripts?

Senior Engineering Answer

Registering trap cleanup EXIT runs automatically whether the script succeeds, fails under set -e, or exits early. Note that in Bash, EXIT traps also fire after INT/TERM if you explicitly exit in their handlers (or simply trap EXIT while letting INT/TERM exit cleanly). Always create temporary directories/files with mktemp rather than predictable /tmp/foo.$$ names (which are vulnerable to symlink race attacks).

Production Code Example
#!/usr/bin/env bash
set -euo pipefail

tmp_dir="$(mktemp -d)"
cleanup() {
  local rc=$?
  rm -rf -- "$tmp_dir"
  exit "$rc"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
Common Interview Trap / Anti-Pattern:

Passing double quotes when defining a trap like trap "rm -rf $tmp_dir" EXIT evaluates $tmp_dir at definition time; if $tmp_dir changes later or was not yet set, it traps an empty or stale path. Use a cleanup function instead.

Question #9AdvancedSenior

What subtle pitfalls defeat set -e (errexit) in production scripts, and how does local val=$(failing_cmd) silently swallow errors?

Senior Engineering Answer

In Bash, local, export, and declare are builtin commands whose exit status reflects whether the declaration succeeded—NOT the exit status of the command substitution inside them! Thus local out=$(false) returns 0 and never triggers set -e. Additionally, calling a function as part of an ||, &&, or if condition disables errexit inside the ENTIRE body of that function (even on earlier lines before the return!). Always declare local variables on one line and assign them on the next.

Production Code Example
# WRONG: local masks exit code of curl
# local body=$(curl -fsSL https://bad.example)

# RIGHT: separate declaration from assignment
local body
body="$(curl -fsSL https://api.example.com/health)"
Common Interview Trap / Anti-Pattern:

Calling check_deploy || echo "warn" disables set -e for every single statement inside check_deploy, allowing destructive failures halfway through the function to proceed.

Question #10AdvancedSenior

Explain file descriptor redirection ordering (2>&1 >file vs >file 2>&1) and how exec can manage custom FDs and logging.

Senior Engineering Answer

Bash processes redirections strictly left-to-right by duplicating file descriptor pointers. In >out.log 2>&1, FD 1 is first pointed to out.log, and then FD 2 is pointed to whatever FD 1 currently targets (out.log)—sending both stdout and stderr to the file. Reversing them (2>&1 >out.log) points FD 2 to the original terminal stdout, then redirects only FD 1 to out.log. Using exec allows permanent script-wide redirections or opening custom FDs (e.g., FD 3 for structured output, FD 9 for flock).

Production Code Example
# Open FD 9 on a lockfile to enforce single-instance execution
exec 9>/var/lock/nightly-sync.lock
if ! flock -n 9; then
  printf 'Another instance is running\n' >&2
  exit 1
fi
Common Interview Trap / Anti-Pattern:

Using custom FDs above 9 in older shells or hardcoded numbers can collide with Bash's internal FDs; in Bash 4.1+, prefer automatic FD allocation via exec {lock_fd}>/var/lock/app.lock.

Question #11AdvancedSenior

How do you prevent command injection and flag injection when building dynamic commands in Bash?

Senior Engineering Answer

Never concatenate command strings and pass them to eval or bash -c "$cmd" with untrusted input, and never store flags and arguments in a plain string variable ($FLAGS). Instead, construct commands as Bash arrays (args=("--tag" "$user_tag")) and execute them via "${args[@]}". This preserves exact argument boundaries without re-parsing quotes or globs. Use -- to terminate option parsing before user-supplied paths, and sanitize or validate inputs with strict regex allowlists.

Production Code Example
run_docker_build() {
  local tag="$1"
  [[ $tag =~ ^[a-zA-Z0-9._-]+$ ]] || { printf 'Invalid tag\n' >&2; return 1; }

  local -a cmd=(docker build --pull -t "app:${tag}" .)
  "${cmd[@]}"
}
Common Interview Trap / Anti-Pattern:

Quoting a string variable like "$ARGS" passes all flags as a single literal argument, while leaving $ARGS unquoted exposes the command to word splitting and glob injection.

Question #12AdvancedSenior

How do associative arrays (declare -A) and namerefs (local -n) work in Bash 4+, and what circular-reference bugs can namerefs cause?

Senior Engineering Answer

declare -A creates hash maps indexed by arbitrary strings (e.g., counts["$key"]=1), ideal for grouping log fields or caching lookups without temporary files. local -n ref="$1" creates a nameref alias pointing to the caller's variable by name so functions can mutate arrays or maps in place without subshell serialization. However, if the caller's variable happens to share the exact same name as the nameref parameter inside the callee (e.g., passing 'arr' into a function with local -n arr="$1"), Bash throws a circular name reference error.

Production Code Example
increment_metric() {
  local -n _target_map="$1" # Prefix internal namerefs to avoid collision
  local key="$2"
  _target_map["$key"]=$(( ${_target_map["$key"]:-0} + 1 ))
}

declare -A metrics=()
increment_metric metrics "http_200"
printf '200s: %d\n' "${metrics[http_200]}"
Common Interview Trap / Anti-Pattern:

Associative array keys inside arithmetic context like (( counts[$key]++ )) undergo extra expansion and can execute arbitrary code if $key contains array syntax; sanitize keys or use explicit lookup.

Question #13StaffPrincipal / Staff

How do you write a container ENTRYPOINT script in Bash that handles PID 1 signal forwarding and graceful shutdown properly?

Senior Engineering Answer

In Linux containers, PID 1 does not get default kernel handlers for SIGTERM or SIGINT, and Bash does not forward signals to foreground child processes automatically. If an entrypoint finishes setup and runs the application without exec, Bash stays PID 1, ignores docker stop's SIGTERM, and the container gets SIGKILLed after the grace timeout. Replacing the shell process via exec "$@" hands PID 1 directly to the target binary; if the shell must stay alive as a wrapper, launch the child in the background, trap SIGTERM/SIGINT to kill -TERM "$child_pid", and wait "$child_pid".

Production Code Example
#!/usr/bin/env bash
set -euo pipefail

# Option A: Hand PID 1 directly to the application
if [[ $# -gt 0 ]]; then
  exec "$@"
fi
Common Interview Trap / Anti-Pattern:

Running wait inside a Bash script pauses signal trap execution until the foreground command exits unless the child is backgrounded (&) and waited on.

Question #14StaffPrincipal / Staff

How do you parallelize work safely in Bash with bounded concurrency, exit-code aggregation, and zero zombie/orphan processes?

Senior Engineering Answer

For streaming file or item workloads, xargs -0 -P "$workers" -n 1 handles bounded parallelism cleanly without shell job-control complexity. When orchestration logic lives inside Bash functions, maintain a worker pool using background jobs (&), track PIDs, and throttle concurrency in Bash 4.3+ with wait -n (or jobs -rp count) so at most N workers run concurrently, collecting each worker's exit status explicitly via wait "$pid". Pair with an EXIT/TERM trap that sends SIGTERM to active child PIDs.

Production Code Example
run_pool() {
  local max_jobs=4 failures=0
  local -a pids=()

  for target in "$@"; do
    while (( $(jobs -rp | wc -l) >= max_jobs )); do
      wait -n || ((++failures))
    done
    process_target "$target" &
    pids+=("$!")
  done

  for pid in "${pids[@]}"; do
    wait "$pid" || ((++failures))
  done
  return "$failures"
}
Common Interview Trap / Anti-Pattern:

Calling plain wait with no arguments returns 0 even if background jobs failed! You must inspect wait -n or wait "$pid" for each PID to propagate failures.

Question #15StaffPrincipal / Staff

How do you debug silent production failures, enable high-signal execution tracing (PS4), and enforce quality gates with ShellCheck and BATS?

Senior Engineering Answer

Set export PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}(): ' alongside set -x (or send trace output solely to a dedicated FD via BASH_XTRACEFD) so xtrace logs include timestamps, source file, line number, and function without polluting stdout data streams. In CI, enforce ShellCheck (with explicit error budgets and # shellcheck disable=... justifications) plus shfmt formatting, and test critical CLI logic using BATS (Bash Automated Testing System) with mocked PATH binaries.

Production Code Example
exec 5>>/var/log/deploy-trace.log
export BASH_XTRACEFD=5
export PS4='+ $(date +%H:%M:%S) ${BASH_SOURCE[0]##*/}:${LINENO}: '
set -x
Common Interview Trap / Anti-Pattern:

Enabling set -x globally in scripts that handle secrets leaks tokens directly into CI logs; wrap secret-handling sections with { set +x; } 2>/dev/null and restore only around non-sensitive logic.

Question #16StaffPrincipal / Staff

When should a team stop extending a Bash script and migrate it to Python or Go, and how do you govern shell tooling across an engineering org?

Senior Engineering Answer

Bash excels as glue for process pipelines, container entrypoints, and simple environment bootstraps under ~150 lines. Once a script needs nested JSON/YAML parsing beyond simple jq queries, complex error recovery, structured concurrency, network retries, or unit-tested state machines, maintaining it in Bash incurs severe defect rates from word-splitting, subshell scoping, and OS utility flag drift (GNU vs BSD sed/date). An engineering org sets a clear threshold (e.g., >150–200 lines or non-trivial data structures -> rewrite in Go/Python), enforces #!/usr/bin/env bash + ShellCheck in CI, and bans curl|bash patterns in favor of pinned, checksum-verified artifacts.

Production Code Example
# Checksums before executing downloaded tools instead of curl | bash
curl -fsSLO "https://releases.example.com/tool-v1.4.2-linux-amd64.tar.gz"
printf '%s  %s\n' "$EXPECTED_SHA256" "tool-v1.4.2-linux-amd64.tar.gz" | sha256sum -c -
Common Interview Trap / Anti-Pattern:

Relying on GNU-specific flags like sed -i or date -d without checking portability silently breaks developers running macOS BSD userland.

Bash Scripting Track Coverage & Difficulty Profile

16 of 16 prompts include code examples

This Bash Scripting preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Cloud, DevOps & Systems.

JuniorFundamental

Why should almost every variable expansion in Bash be double-quoted ("$var"), and how do "$@" and "$*" differ?

JuniorFundamental

What is the difference between [ ] (test), [[ ]] (extended test), and (( )) (arithmetic evaluation) in Bash?

JuniorFundamental

What does set -euo pipefail do, and why is it called unofficial Bash strict mode?

JuniorFundamental

How do Bash parameter expansions like ${var:-default}, ${var:?msg}, ${var##*/}, and ${var%/*} eliminate external sed/awk calls?

Mid-LevelIntermediate

Why does a pipeline like cmd | while read -r line; do count=$((count+1)); done lose updates to count, and how do you fix it?

Mid-LevelIntermediate

How do you safely iterate over arbitrary filenames (including spaces, newlines, and leading hyphens) in Bash without breaking on word splitting?

Frequently Asked Technical Interview Questions (Bash Scripting)

Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.

Why should scripts start with #!/usr/bin/env bash instead of #!/bin/bash or #!/bin/sh?
#!/bin/sh invokes a minimal POSIX shell (such as dash on Debian/Ubuntu) where Bash features like [[ ]], arrays, and process substitution fail. #!/usr/bin/env bash searches PATH so it works on Linux, macOS (Homebrew Bash), and NixOS where Bash may not reside at /bin/bash.
What is the difference between $(command) and legacy backticks `command`?
$(command) is POSIX-compliant, handles backslashes predictably, and nests cleanly without awkward escaping (e.g., $(dirname "$(readlink -f "$0")")). Backticks require multi-level backslash escaping when nested and reduce readability.
Why is printf preferred over echo in portable and production Bash scripts?
echo behavior varies across shells and implementations when strings start with -n/-e or contain backslash escapes. printf '%s\n' "$var" behaves identically everywhere and never interprets flags or escapes inside the variable argument.
How do single quotes, double quotes, and ANSI-C quoting ($'...') differ in Bash?
Single quotes preserve every character literally with zero expansions. Double quotes allow parameter ($var), command ($(...)), and arithmetic ($((...))) expansion while suppressing word splitting and globbing. ANSI-C quoting ($'line1\nline2') interprets escape sequences like \n, \t, and \x1b cleanly.
Complete Learning Ecosystem

Pair Interview Prep with Cheat Sheets & Roadmaps

Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.

Want to practice other technologies?

Explore our comprehensive technical interview tracks across all core technology stacks.

Browse All Interview Tracks