Autocoder

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.

Shellbash 4 or newer unless stated
TopicsQuoting, tests, loops, functions, exit codes, strict mode, trap, getopts, arrays
Code10 scripts and snippets

Three habits that avoid most bugs

Shell Scripting Interview Questions with Bash Examples: questions with worked answers

  1. 1

    What is a shebang line and how do you run a script?

    easy

    The 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. 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"; done
  3. 3

    What is the difference between single quotes, double quotes and no quotes?

    medium

    Single 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".

    bash
    name="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 file
  4. 4

    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.

    bash
    if [[ -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. 5

    Write a loop that processes every .log file in a directory and counts the ERROR lines in each.

    medium

    Use 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"
    done
  6. 6

    How do you read a file line by line safely?

    medium

    Use 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.

    bash
    count=0
    while IFS= read -r line; do
      [[ -z "$line" ]] && continue
      count=$((count + 1))
    done < input.txt
    echo "non-empty lines: $count"
  7. 7

    How do you define a function, return a value and use local variables?

    medium

    Functions 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.

    bash
    add() {
      local a=$1 b=$2
      echo $((a + b))
    }
    sum=$(add 3 4)
    echo "sum is $sum"       # sum is 7
  8. 8

    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 unset
  9. 9

    How do you handle cleanup when a script exits or is interrupted?

    medium

    trap 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.

    bash
    tmp=$(mktemp -d)
    trap 'rm -rf "$tmp"' EXIT
    curl -s https://example.com -o "$tmp/page.html"
    wc -c "$tmp/page.html"
  10. 10

    How do you parse command-line options in a script?

    medium

    getopts 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.

    bash
    verbose=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. 11

    Show string manipulation in bash: length, substring, remove extension and replace.

    medium

    Parameter 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.

    bash
    s="/home/user/report.txt"
    echo "${#s}"          # 21
    echo "${s##*/}"       # report.txt
    echo "${s%.txt}"      # /home/user/report
    echo "${s//e/E}"      # /homE/usEr/rEport.txt
  12. 12

    How do you use arrays and associative arrays?

    medium

    Indexed 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.

    bash
    fruits=("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]}"; done
  13. 13

    Write a function that retries a command up to 3 times with a delay.

    hard

    Loop 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.

    bash
    retry() {
      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/health
  14. 14

    What is the difference between sourcing a script and executing it, and between a subshell and the current shell?

    hard

    Running ./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. 15

    Explain process substitution and a here document.

    hard

    Process 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.

    bash
    diff <(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

More in CS Fundamentals Interview Questions

See all in this section