Bash Scripting Interview Questions
Shell scripting technical guide: POSIX compliance, parameter expansion, subshell execution, piping backpressure, trap signal handling, and robust script debugging.
Practice Bash Scripting Interview Questions
Showing 16 of 16 technical questions with engineering explanations
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.
backup_files() {
local dest="$1"
shift
# Preserves spaces in filenames passed as separate args
cp -- "$@" "$dest/"
}Using $@ without double quotes behaves just like unquoted $*, silently breaking filenames containing spaces.
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.
name="deploy prod.log"
if [[ -f $name && $name == *.log ]]; then
count=5
if (( count > 3 )); then
printf 'Found %d logs\n' "$count"
fi
fiIn [[ $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 =~.
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.
#!/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[]'
Do not assume set -e catches everything: commands inside if conditions, || / && lists, and subshells inside local var=$(cmd) bypass errexit.
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.
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/appConfusing :- (unset OR empty) with - (only unset), and forgetting that ${var:-default} does not assign the default back to var—use ${var:=default} for assignment.
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).
count=0 while IFS= read -r line; do ((++count)) done < <(printf 'a\nb\nc\n') printf 'Total lines: %d\n' "$count" # Prints 3
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)).
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.
while IFS= read -r -d '' file; do printf 'Processing: %q\n' "$file" chmod 0644 -- "$file" done < <(find /var/uploads -type f -name '*.txt' -print0)
Omitting IFS= causes read to trim leading and trailing whitespace from filenames; omitting -r causes read to interpret backslashes as escape characters.
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).
# 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
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.
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).
#!/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' TERMPassing 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.
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.
# 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)"
Calling check_deploy || echo "warn" disables set -e for every single statement inside check_deploy, allowing destructive failures halfway through the function to proceed.
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).
# 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
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.
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.
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[@]}"
}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.
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.
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]}"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.
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".
#!/usr/bin/env bash set -euo pipefail # Option A: Hand PID 1 directly to the application if [[ $# -gt 0 ]]; then exec "$@" fi
Running wait inside a Bash script pauses signal trap execution until the foreground command exits unless the child is backgrounded (&) and waited on.
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.
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"
}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.
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.
exec 5>>/var/log/deploy-trace.log
export BASH_XTRACEFD=5
export PS4='+ $(date +%H:%M:%S) ${BASH_SOURCE[0]##*/}:${LINENO}: '
set -xEnabling 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.
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.
# 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 -
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 examplesThis 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.
Why should almost every variable expansion in Bash be double-quoted ("$var"), and how do "$@" and "$*" differ?
What is the difference between [ ] (test), [[ ]] (extended test), and (( )) (arithmetic evaluation) in Bash?
What does set -euo pipefail do, and why is it called unofficial Bash strict mode?
How do Bash parameter expansions like ${var:-default}, ${var:?msg}, ${var##*/}, and ${var%/*} eliminate external sed/awk calls?
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?
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?
What is the difference between $(command) and legacy backticks `command`?
Why is printf preferred over echo in portable and production Bash scripts?
How do single quotes, double quotes, and ANSI-C quoting ($'...') differ in Bash?
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.