Shell scripting interview questions: bash, quoting and script reviews
Shell scripting interview questions test whether your scripts survive real input: filenames with spaces, commands that fail halfway, missing arguments and a different shell on the server. Expect quoting and expansion puzzles, output prediction, a short script written live and a review of someone else's script. The answers that score are the ones that name the failure a line of code prevents.
By Evin JohnPublished 10 min read
How shell scripting is tested in interviews
Bash questions show up in DevOps, SRE, systems administration, build and release, data engineering and backend loops, usually inside a broader Linux round. The formats repeat across companies. A quick-fire round asks what a construct does. An output-prediction round shows six lines and asks what they print. A live task asks for a 20 to 40 line script, often in a shared editor with no way to run it. A review round hands you a script that "works on my machine" and asks what will break. Interviewers read quoting the way a code reviewer reads null checks: one unquoted variable in the wrong place is enough to start a follow-up.
Fundamentals
| Question | What it tests | What a strong answer shows |
|---|---|---|
What does the first line #!/usr/bin/env bash do? | How scripts start | The kernel reads the shebang and runs the named interpreter with the script as an argument. Going through env finds bash on the PATH, which helps where bash is not in /bin, at the cost of trusting the PATH. |
What is the difference between running ./deploy.sh and source deploy.sh? | Process model | Running it starts a child process, so its variables and cd die with it. Sourcing runs it in the current shell, so it can change your environment, which is the point of files like a virtualenv's activate script. |
| How do you read the exit status of the last command? | Status codes | $? holds it: 0 means success, anything from 1 to 255 means failure. It is overwritten by the next command, so save it right away if you need it twice. |
| Single quotes versus double quotes? | Quoting | Single quotes keep every character literal. Double quotes still expand variables, command substitution and arithmetic, but stop word splitting and glob expansion of the result. |
Why prefer $(command) over backticks? | Style and nesting | It nests without escaping, reads clearly and treats backslashes predictably. Backticks still work but are legacy. |
What does export change? | Environment | It marks a variable to be copied into the environment of child processes. Without it the variable exists only in the current shell. A child can never change its parent's variables. |
[ versus [[ in bash? | Tests | [ is a command (also called test) that sees words after splitting, so unquoted variables can break it. [[ is bash syntax: no word splitting inside, pattern matching with ==, regex with =~, and && and || inside the brackets. It is not POSIX. |
| What do exit codes 126, 127 and 130 usually mean? | Debugging | 126: found but not executable. 127: command not found. Codes above 128 mean a signal ended the process, 128 plus the signal number, so 130 is Ctrl+C (SIGINT) and 137 is SIGKILL. |
| How do you write a here-document, and why quote its delimiter? | Multi-line input | cat <<EOF feeds the lines up to EOF as standard input with expansions applied. Writing <<'EOF' turns expansions off, which you want when generating a script or config that contains its own dollar signs. |
What is the difference between $* and "$@"? | Arguments | Unquoted, both split and glob every argument. Quoted, "$*" joins all arguments into one string while "$@" keeps each one as a separate word, spaces included, so it is the right way to pass arguments through. |
Quoting, expansion and word splitting
- In what order does bash expand a command line? Brace expansion, then tilde, parameter, arithmetic and command substitution, then word splitting on the unquoted results, then pathname (glob) expansion, then quote removal. Most quoting bugs come from the last two steps acting on data you did not expect.
- What does IFS control? The characters used for word splitting and by
readto split fields. Its default is space, tab and newline. SettingIFS=for a singlereadkeeps leading and trailing spaces in the line. - Why `read -r`? Without -r, a backslash in the input escapes the next character and disappears. With -r the line arrives exactly as written, which is almost always what you want.
- Give five parameter expansions you use.
${name:-fallback}for a default,${name:?message}to stop when a required value is empty,${path##*/}to keep the part after the last slash,${file%.log}to drop a suffix, and${#name}for the length. Bash adds${name//old/new}to replace every match. - How do arrays help with commands that take many arguments? Build the arguments in an array,
opts=(--verbose --output "$out"), and expand it as"${opts[@]}". Each element stays one word even when it contains spaces, which a space-joined string cannot do. - What does `echo` do differently from `printf`? Implementations of echo disagree on flags like -e and -n and on backslash handling. printf behaves the same everywhere and takes a format string, so scripts that must be portable use it.
- Why can `ls | while read` go wrong? Parsing ls output breaks on unusual names and its format is meant for people. Loop over a glob (
for f in ./*.csv) or use find with null separators instead.
Output prediction is a favorite because it reveals whether you understand subshells. Ask yourself what this prints before reading the answer below it.
#!/usr/bin/env bash
count=0
printf 'a\nb\nc\n' | while IFS= read -r line; do
count=$(( count + 1 ))
done
echo "after the pipe: $count"
count=0
while IFS= read -r line; do
count=$(( count + 1 ))
done < <(printf 'a\nb\nc\n')
echo "after process substitution: $count"Exit statuses, functions and error handling
| Question | What it tests | What a strong answer shows |
|---|---|---|
| How does a function return a value? | Functions | return only sets a status from 0 to 255. Real data comes back on standard output and is captured with $(...), or through a global variable when performance matters. |
return versus exit inside a function? | Control flow | return leaves the function with a status. exit ends the whole script, or only the subshell when the function runs inside $(...) or a pipe, which surprises people. |
What does errexit (set -e) not catch? | Error handling | Failures in an if or while condition, on the left of && or ||, in a negated command, and in every pipeline stage except the last unless pipefail is on. Functions called from such a context lose errexit too. |
Why can local out=$(cmd) hide an error? | Masked status | The status of the line is the status of local, which succeeds. Declare first, then assign: local out; out=$(cmd), so a failing command can be checked. |
Can (( count++ )) stop a script? | Arithmetic status | An arithmetic command returns 1 when the expression is 0. With a counter starting at 0, the post-increment evaluates to 0, so under errexit in current bash the script ends. Write count=$(( count + 1 )) instead. |
What does trap handle? | Signals | It runs a command when the shell gets a signal (INT, TERM, HUP) or on pseudo-signals: EXIT when the script ends, ERR when a command fails. Common uses are killing child processes on Ctrl+C and printing the failing line number with ERR. |
| Can a trap catch SIGKILL? | Signal basics | No. SIGKILL and SIGSTOP cannot be caught or ignored, so cleanup that must always happen needs another safety net, such as a startup check for leftovers. |
| How do you check that a command exists before using it? | Dependencies | command -v jq >/dev/null || { echo 'jq is required' >&2; exit 1; }. command -v is POSIX; which is an external program whose output varies by system. |
What does -- do in rm -- "$file"? | Option parsing | It ends option parsing, so a file named -rf or --help is treated as a name and not as flags. |
| How would you make a script refuse to run twice at the same time? | Locking | On Linux, flock on a lock file is the usual answer. A portable version uses mkdir as an atomic test-and-create of a lock directory, removed in an EXIT trap, with a way to clear a stale lock. |
#!/usr/bin/env bash
# retry MAX_TRIES COMMAND [ARGS...]
# Runs the command until it succeeds, doubling the pause after each failure.
# Returns 0 on success, or the command's last exit status when it gives up.
retry() {
local max_tries=${1:?usage: retry MAX_TRIES COMMAND...}
shift
local attempt=1 pause=1 status
while true; do
"$@" && return 0
status=$?
if (( attempt >= max_tries )); then
printf 'retry: giving up after %d tries (status %d): %s\n' "$attempt" "$status" "$*" >&2
return "$status"
fi
printf 'retry: try %d failed (status %d), sleeping %ds\n' "$attempt" "$status" "$pause" >&2
sleep "$pause"
attempt=$(( attempt + 1 ))
pause=$(( pause * 2 ))
done
}
retry 5 curl --fail --silent --show-error --output /tmp/health.json https://example.com/healthA live scripting task: options, files and edge cases
A common live task is a small tool with a flag or two that walks a directory. The interviewer is less interested in the gzip call than in the scaffolding: a usage message on bad input, validated arguments, a dry-run mode and file handling that does not break on odd names. Talk through each guard as you add it.
#!/usr/bin/env bash
# archive-logs: gzip *.log files older than DAYS days under DIR.
# usage: archive-logs [-n] [-d DAYS] DIR (-n = dry run, only print)
set -o errexit -o nounset -o pipefail
usage() { printf 'usage: %s [-n] [-d DAYS] DIR\n' "${0##*/}" >&2; exit 2; }
dry_run=false
days=7
while getopts ':nd:' opt; do
case $opt in
n) dry_run=true ;;
d) days=$OPTARG ;;
:) printf 'option -%s needs a value\n' "$OPTARG" >&2; usage ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
(( $# == 1 )) || usage
dir=${1}
[[ $days =~ ^[0-9]+$ ]] || { echo "DAYS must be a whole number" >&2; exit 2; }
[[ -d $dir ]] || { echo "not a directory: $dir" >&2; exit 1; }
count=0
while IFS= read -r -d '' file; do
if [[ $dry_run == true ]]; then
printf 'would compress: %s\n' "$file"
else
gzip -- "$file"
fi
count=$(( count + 1 ))
done < <(find "$dir" -type f -name '*.log' -mtime +"$days" -print0)
echo "$count file(s) handled"- Follow-up: why the leading colon in `':nd:'`? It switches getopts to silent mode, so the script prints its own message for a missing value (the
:case) or an unknown flag (the*case) instead of the shell's generic one. - Follow-up: why `-mtime +7` and not `-mtime 7`? Plus means strictly more than seven whole days old; a bare number means exactly that many days, which almost never matches what people intend.
- Follow-up: how would you process the files in parallel?
find ... -print0 | xargs -0 -P 4 -n 20 gzip --runs four gzip processes at a time. Mention that output from parallel jobs interleaves and that error counting becomes harder.
Review round: find the bugs
#!/bin/bash
# Clean the build output of every project passed on the command line.
for project in $*; do
cd $project
rm -rf $BUILD_DIR/*
cd ..
done
echo "cleaned"$*unquoted splits a project namedmy appinto two words, and a name with*in it globs.- A failed
cdis ignored, so thermruns in whatever directory the script happens to be in. - If BUILD_DIR is unset or empty, the command becomes
rm -rf /*. Use"${BUILD_DIR:?}"so an empty value stops the script. cd ..only returns to the start when every project is exactly one level deep. Run each iteration in a subshell,( cd -- "$project" && ... ), or use absolute paths.- It always prints "cleaned" and exits 0, even when every iteration failed. Track failures and exit non-zero.
- A safer loop:
for project in "$@"; do ( cd -- "$project" && rm -rf -- "${BUILD_DIR:?}"/* ) || failed=1; done.
Portability: sh, bash and two kinds of tools
| Question | What it tests | What a strong answer shows |
|---|---|---|
Is /bin/sh the same as bash? | Shell landscape | Not necessarily. On Debian and Ubuntu it is dash, a small POSIX shell; on macOS it is bash running in POSIX mode. A script with arrays or [[ and a #!/bin/sh line works on one and fails on the other. |
| Which bash features are not POSIX? | Portability | Arrays, [[ ]], (( )), process substitution, ${var//a/b}, local in a strict reading, source (POSIX spells it .), function keyword, and brace expansion like {1..5}. |
Why does the same sed -i line fail on a Mac? | GNU versus BSD | BSD sed requires a suffix argument after -i (an empty '' for none) while GNU sed takes it attached or not at all. date, stat and grep options differ the same way. |
| Which bash version will run your script? | Versions | macOS ships the old bash 3.2 as /bin/bash, while Linux distributions ship bash 5. Associative arrays (declare -A), mapfile and case conversion with ${name,,} need bash 4 or later. |
| How do you lint a shell script? | Tooling | ShellCheck catches unquoted expansions, unused variables, useless cat, broken tests and many portability problems. Running it in CI is a quick win worth mentioning. |
Senior and scenario questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| A deploy script printed a database password into the CI log. | Secrets | set -x echoes expanded commands, and passwords passed as arguments are visible in ps to other users. Read secrets from files or the environment, turn tracing off around them, and use the CI system's masking. |
| A script hangs forever in the pipeline but works in a terminal. | Interactivity | Something is waiting on standard input or a TTY: a prompt from ssh, apt, git or sudo. Pass non-interactive flags, redirect stdin from /dev/null, and add timeouts around network calls. |
| You need to call an API for 2,000 IDs with a rate limit. | Throughput | xargs -P with a small concurrency, retries with backoff for 429 and 5xx responses, results written per ID so a rerun skips finished work, and a summary of failures at the end. |
| A script grew to 600 lines with nested JSON handling. | Judgment | Say when to stop: complex data structures, real error handling, unit tests and JSON beyond a jq one-liner are signs to move to Python or Go. Keep the shell for gluing commands together. |
| Two cron runs overlapped and corrupted an output file. | Concurrency | Add a lock, write to a temporary file in the same directory and rename it into place, since a rename on the same filesystem is atomic, so readers never see a half-written file. |
| Ctrl+C stops the script but its background jobs keep running. | Process groups | Trap INT and TERM, kill the recorded child PIDs (or the process group) and wait for them, then exit with 128 plus the signal number so callers see an interrupt. |
Fictional example
- Interviewer
- Here is the loop we use to clean build folders. It has worked for a year. Anything you would change?
- Candidate
- Yes, and I would fix one thing today. If BUILD_DIR is ever empty, say a CI job forgets to set it, the rm line expands to rm -rf /*. I would write it with the :? expansion so an empty value stops the script before rm runs. Second, nothing checks the cd. If a project folder was renamed, the rm runs in the previous directory. I would run each project in a subshell with cd -- "$project" && rm, which also removes the cd .. that only works one level deep. Third, the loop uses an unquoted star, so a project with a space in its name splits in two; quoted "$@" fixes that. Last, it reports success no matter what, so I would set a flag on any failure and exit 1 at the end so CI notices. Then I would run ShellCheck on it, because it flags most of this automatically.
How to prepare for shell scripting interview questions
- Break your own scriptsCreate files named with spaces, a leading dash, a star and a newline, then run your scripts against them. Fix each failure and note which quoting rule it taught you.
- Write five tools from scratchA retry helper, a getopts CLI, a directory walker, a parallel downloader with xargs and a lock-protected cron job. Time yourself writing each in a plain editor without running it, then run it.
- Drill output predictionPipes and subshells,
"$*"versus"$@", unquoted globs, errexit inside conditions, and local hiding a status. Predict, then check in a terminal. - Test on two shellsRun your scripts with bash and with dash as sh, and on both GNU and BSD tools if you can. Note every difference you find.
- Run ShellCheck on everythingRead each warning's explanation. Interviewers often ask about exactly the issues it reports.
Related reading: the Linux interview questions page covers processes, permissions and troubleshooting that scripting rounds lean on, PowerShell interview questions covers the Windows side of automation, and Nginx interview questions covers the server config that shell scripts so often reload and test.
Review rounds are mostly talk, so the habit worth building is naming the bug and its consequence in one breath. Natively, an AI interview assistant for Mac and Windows, can transcribe a mock scripting round, read a script or an error message from a screenshot, and show a suggested fix beside your own answer while you practice. With Pro or the free trial it also draws on the résumé and job description you add, and each session's transcript and notes stay available to look back at.
Questions people ask
What are common shell scripting interview questions?
Single versus double quotes, "$@" versus "$*", how to read an exit status, what set -e misses, how getopts parses flags, what trap does, and how to loop over files whose names contain spaces.
Why does a variable set inside a piped while loop disappear in bash?
Each part of a pipe runs in a subshell by default, so the loop changes a copy. Feed the loop with process substitution or a redirect instead, or enable lastpipe in bash 4.2 and later.
Is bash scripting the same as sh scripting?
No. sh means a POSIX shell, which may be dash or bash in POSIX mode. Arrays, [[ ]], (( )) and process substitution are bash features that a plain sh may reject.
How do I practice shell scripting for interviews?
Write small tools such as a retry helper and a getopts CLI, test them on file names with spaces and newlines, predict the output of tricky snippets, and run ShellCheck on every script.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
