Shell Scripting Interview Questions with Bash Examples
Last updated 2026-11-19
Shell scripting questions combine small facts (what does $? hold, what is the difference between $@ and $*) with short scripts you write on the spot: check whether a file exists, loop over files, parse a log, or retry a command. The most common source of wrong answers is quoting. A script that works with simple names breaks the moment a file name contains a space.
The examples below target bash on Linux and every one is runnable as written. If the commands used inside the scripts are unfamiliar, see Linux commands interview questions first, and for the system concepts behind them Linux interview questions. Scripting is also a standard part of DevOps interviews.
| Shell | bash 4 or newer unless stated |
|---|---|
| Topics | Quoting, tests, loops, functions, exit codes, strict mode, trap, getopts, arrays |
| Code | 10 scripts and snippets |
Three habits that avoid most bugs
- Quote every variable expansion: "$file", not $file. Unquoted values are split on spaces and expanded as globs.
- Start serious scripts with set -euo pipefail so errors, unset variables and failures inside pipelines stop the script instead of passing silently.
- Use [[ ]] for tests in bash and $(command) for command substitution rather than backticks.
Shell Scripting Interview Questions with Bash Examples: questions with worked answers
1 What is a shebang line and how do you run a script?
easyThe first line #!/bin/bash tells the kernel which interpreter should execute the file; #!/usr/bin/env bash finds bash on the PATH, which is more portable. To run it, make it executable with chmod +x script.sh and call ./script.sh, or run bash script.sh directly, which ignores the shebang and needs no execute bit.
2 What are the special variables $0, $1, $#, $@, $*, $? and $$?
easy$0 is the script name, $1 to $9 are positional arguments, $# is the argument count, $@ is all arguments as separate words, $* is all arguments as one word when quoted, $? is the exit status of the last command (0 means success) and $$ is the shell's own PID. "$@" is almost always what you want when forwarding arguments, because it preserves each argument even if it contains spaces.
bash#!/bin/bash echo "script: $0, args: $#" for a in "$@"; do echo "arg: $a"; done3 What is the difference between single quotes, double quotes and no quotes?
mediumSingle quotes keep everything literal. Double quotes allow variable and command expansion ($var, $(cmd)) but prevent word splitting and globbing. Without quotes the result of an expansion is split on whitespace and glob characters are expanded. So with name="a b", rm $name runs rm a b (two files), while rm "$name" removes one file named "a b".
bashname="my file.txt" echo '$name' # prints: $name echo "$name" # prints: my file.txt touch $name # creates two files: my and file.txt (bug) touch "$name" # creates one file4 How do you test conditions? Compare [ ] and [[ ]].
medium[ is the POSIX test command, so it needs spaces and quoting, and it uses -eq, -lt for numbers and = for strings. [[ ]] is a bash keyword that does not word-split variables, supports pattern matching (==, =~ for regex) and && and || inside. Use -f (is a regular file), -d (directory), -z (string is empty), -n (not empty) and (( )) for arithmetic comparison.
bashif [[ -f "$1" && -r "$1" ]]; then echo "readable file" elif [[ "$1" =~ ^[0-9]+$ ]]; then echo "a number" else echo "something else" fi (( count > 10 )) && echo "big"5 Write a loop that processes every .log file in a directory and counts the ERROR lines in each.
mediumUse a glob in a for loop, not ls, because the glob handles spaces and keeps each name intact. grep -c counts matching lines, and the test guards the case where the glob matches nothing.
bash#!/bin/bash for f in /var/log/app/*.log; do [[ -e "$f" ]] || continue n=$(grep -c "ERROR" "$f") echo "$f: $n" done6 How do you read a file line by line safely?
mediumUse while read with IFS= and -r so leading whitespace and backslashes are preserved, and feed the file by redirecting into the loop. Piping into while runs the loop in a subshell, so variables set inside would be lost; redirecting avoids that.
bashcount=0 while IFS= read -r line; do [[ -z "$line" ]] && continue count=$((count + 1)) done < input.txt echo "non-empty lines: $count"7 How do you define a function, return a value and use local variables?
mediumFunctions are called like commands. return sets only an exit status from 0 to 255. To return data, print it and capture it with command substitution. Declare variables with local to avoid leaking into the global scope.
bashadd() { local a=$1 b=$2 echo $((a + b)) } sum=$(add 3 4) echo "sum is $sum" # sum is 78 What does set -euo pipefail do?
medium-e exits the script when a command fails (returns non-zero), -u treats use of an unset variable as an error, and -o pipefail makes a pipeline fail if any stage fails, not just the last one. Together they turn silent failures into early stops. Caveats: -e does not trigger inside conditions such as if cmd or cmd || true, so some failures are still ignored deliberately.
bash#!/usr/bin/env bash set -euo pipefail cd /srv/app # script stops here if the cd fails echo "deploying $VERSION" # stops if VERSION is unset9 How do you handle cleanup when a script exits or is interrupted?
mediumtrap registers a command to run on a signal or on the EXIT pseudo-signal. Using it with a temp directory guarantees cleanup on normal exit, errors and Ctrl+C. Note that SIGKILL cannot be trapped.
bashtmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT curl -s https://example.com -o "$tmp/page.html" wc -c "$tmp/page.html"10 How do you parse command-line options in a script?
mediumgetopts handles short options. Each letter in the option string is a flag, and a colon after a letter means it takes an argument, stored in OPTARG. After the loop, shift off the parsed options to leave the remaining positional arguments. Long options need manual parsing with case or the external getopt.
bashverbose=0 out=out.txt while getopts "vo:" opt; do case $opt in v) verbose=1 ;; o) out=$OPTARG ;; *) echo "usage: $0 [-v] [-o file] input" >&2; exit 2 ;; esac done shift $((OPTIND - 1)) echo "verbose=$verbose out=$out input=$1"11 Show string manipulation in bash: length, substring, remove extension and replace.
mediumParameter expansion does these without calling external tools. ${#s} gives the length, ${s:2:3} a substring (offset 2, length 3), ${s%.txt} removes a suffix, ${s##*/} removes the longest prefix up to a slash (basename), and ${s//a/b} replaces every a with b.
bashs="/home/user/report.txt" echo "${#s}" # 21 echo "${s##*/}" # report.txt echo "${s%.txt}" # /home/user/report echo "${s//e/E}" # /homE/usEr/rEport.txt12 How do you use arrays and associative arrays?
mediumIndexed arrays use name=(a b c) and are read with ${name[i]}, while "${name[@]}" expands to all elements and ${#name[@]} gives the count. Associative arrays need declare -A (bash 4 or newer) and use string keys. Always quote the expansion to keep elements with spaces intact.
bashfruits=("apple" "banana split" "cherry") echo "${#fruits[@]}" # 3 for f in "${fruits[@]}"; do echo "$f"; done declare -A age=([alice]=30 [bob]=25) age[carol]=41 for k in "${!age[@]}"; do echo "$k is ${age[$k]}"; done13 Write a function that retries a command up to 3 times with a delay.
hardLoop over attempts, run the command, return at the first success and sleep before the next try. Passing the command as "$@" keeps arguments with spaces correct. Returning the last status lets the caller handle a final failure.
bashretry() { local n=1 max=3 delay=2 until "$@"; do if (( n >= max )); then echo "failed after $n attempts" >&2 return 1 fi echo "attempt $n failed, retrying in ${delay}s" >&2 sleep "$delay"; n=$((n + 1)) done } retry curl -fsS https://example.com/health14 What is the difference between sourcing a script and executing it, and between a subshell and the current shell?
hardRunning ./script.sh starts a new child shell, so any variables it sets or directories it changes with cd disappear when it exits. source script.sh (or . script.sh) runs the commands inside the current shell, so they persist; this is how environment files like .bashrc or a virtualenv activate script work. Parentheses ( cmd ) and pipelines also create subshells, so a variable assigned inside them is not visible afterwards.
15 Explain process substitution and a here document.
hardProcess substitution <(cmd) presents the output of a command as a temporary file name, so tools that expect files can read it, as in diff <(sort a) <(sort b). A here document feeds a block of text to a command's stdin until a delimiter line, and quoting the delimiter ('EOF') stops variable expansion inside it. They avoid temporary files and make multi-line input readable.
bashdiff <(sort a.txt) <(sort b.txt) cat > /tmp/conf.ini <<'EOF' [server] port=8080 EOF
Frequently asked questions
What is the difference between bash and sh?
sh is the POSIX shell standard, and on some systems it is a minimal shell such as dash. bash is a superset with arrays, [[ ]], process substitution and more, so a script that uses those must start with #!/bin/bash.
When should I use Python instead of a shell script?
Use shell for gluing commands, simple file operations and short pipelines. Switch to Python when you need data structures, JSON or HTTP handling, proper error handling, tests or more than roughly a hundred lines.
How do I debug a bash script?
Run bash -x script.sh to print each command after expansion, add set -x around a suspect section, use shellcheck for static analysis of quoting and syntax mistakes, and echo values to stderr.
What does the exit code 0 mean?
Zero means success and any non-zero value (1 to 255) means failure, which is the opposite of boolean true and false in most languages. Conditions like if and && test the exit status, so a zero status counts as true.
Related guides
- Linux Commands Interview Questions with Examples
- Linux Interview Questions and Answers: Concepts, Permissions and Processes
- Git Interview Questions and Answers with Commands
- Process and Thread Interview Questions with fork() Output Problems
- Python Interview Questions and Answers
- Docker Interview Questions and Answers
More in CS Fundamentals Interview Questions
- SOLID Principles Interview Questions with Examples
- System Design Interview Questions for Freshers
- System Design Interview Questions with Worked Designs
- TCP vs UDP Interview Questions with Socket Code and Numericals
- TCP/IP Interview Questions: Handshake, Congestion Control and Numericals
- Transactions and ACID Interview Questions
- What Happens When You Type a URL in the Browser: The Complete Answer
- Abstraction and Encapsulation Interview Questions
- Cache Memory and Computer Organization Interview Questions with Numericals
- Caching Interview Questions and Answers
- Cloud Computing Basics Interview Questions with Answers
- Computer Architecture Interview Questions with Numericals