Week 02 Review — Interview Questions¶
Questions covering functions, script structure, error handling, arrays, file ops, regex, automation, and networking.
Functions¶
1. Why should you use local for variables inside functions?
Show answer
Without local, variables are global and can accidentally overwrite variables in the calling scope. local scopes the variable to the function, making functions self-contained and reusable.
2. How do you return a string value from a bash function?
Show answer
Print the value with echo or printf and capture with command substitution: result=$(my_func arg). return can only pass an integer exit code (0-255).
3. What does source file.sh do, and how is it different from bash file.sh?
Show answer
source runs the file in the current shell — functions and variables become available in the current session. bash file.sh runs in a new child process — nothing defined in it persists after it exits.
4. Why must functions be defined before they are called in bash?
Show answer
Bash reads scripts top to bottom. If you call a function before its definition, bash sees command not found. Define or source all functions at the top, or call main "$@" at the very bottom after all definitions.
Script Structure¶
5. What does set -euo pipefail do?
Show answer
-e exits immediately when any command returns non-zero. -u treats unset variables as errors. -o pipefail makes pipelines fail if any stage fails (not just the last). Together they prevent most silent failure modes.
6. Why use #!/usr/bin/env bash instead of #!/bin/bash?
Show answer
/bin/bash hardcodes the path. On macOS with Homebrew, NixOS, or some containers, bash may be in a different location. #!/usr/bin/env bash searches $PATH, making the script portable.
7. How do you handle a command that legitimately returns non-zero when set -e is active?
Show answer
Use command || true to ignore the exit code. Or use if command; then ...; fi — set -e does not trigger inside if conditions. Or temporarily disable with set +e; command; set -e.
Error Handling¶
8. What does trap 'cleanup' EXIT do?
Show answer
Registers a command to run whenever the script exits — normal completion, exit N, or unhandled error. Used for cleanup: removing temp files, releasing locks, restoring state.
9. How do you debug a bash script without adding print statements?
Show answer
bash -x script.sh traces every command. Set PS4 for file/line context. Use set -x / set +x to trace specific sections. bash -n script.sh checks syntax without running.
10. Why might set -e not stop a script when a command inside an if condition fails?
Show answer
-e does not trigger for commands evaluated as conditions — in if, while, until, and after && / ||. The script is explicitly testing for failure in those positions.
String & Array Operations¶
11. What is the difference between ${arr[@]} and ${arr[*]}?
Show answer
When double-quoted: "${arr[@]}" → each element is a separately quoted word. "${arr[*]}" → all elements joined into one string by IFS. Use "${arr[@]}" for iteration and passing to commands.
12. How do you create an associative array in bash?
Show answer
declare -A mymap then mymap["key"]="value". Without declare -A, bash treats it as a regular indexed array. Requires bash 4.0+.
13. What does ${var##*.} extract?
Show answer
The last extension — it removes the longest prefix matching *. (everything up to and including the last dot), leaving just the extension. Example: file="archive.tar.gz" → ${file##*.} gives gz.
File Operations at Scale¶
14. What does the trailing slash mean in rsync -av src/ dest/?
Show answer
A trailing slash on the source means "sync the contents of src, not src itself." Without it: rsync src dest/ creates dest/src/. With it: rsync src/ dest/ copies files directly into dest/.
15. What does tar -czf stand for?
Show answer
c=create, z=gzip compress, f=filename follows. tar -czf archive.tar.gz dir/ creates a compressed archive.
16. Why is -print0 | xargs -0 preferred over for f in $(find ...)?
Show answer
Null bytes cannot appear in filenames, so null-delimited transfer handles filenames with spaces, newlines, and special characters correctly. $(find ...) splits on whitespace and breaks on unusual filenames.
Regular Expressions¶
17. What is the difference between BRE and ERE?
Show answer
BRE (plain grep) requires backslashes before +, ?, (, ), {, }. ERE (grep -E) treats them as special without backslashes. ERE is cleaner for complex patterns.
18. What does grep -o do?
Show answer
Prints only the matched portion of each line, one match per output line. Useful for extracting data: grep -oE '[0-9]+' log.txt extracts all numbers.
19. How do regex capture groups work in bash [[ =~ ]]?
Show answer
After [[ str =~ pattern ]], ${BASH_REMATCH[0]} is the full match, ${BASH_REMATCH[1]} is the first group, etc. The pattern must be unquoted on the right side of =~.
Automation¶
20. What is the most common reason a cron job fails when the command works in the terminal?
Show answer
$PATH differences. Cron's minimal $PATH (/usr/bin:/bin) does not include /usr/local/bin, ~/.local/bin, etc. Fix: use full absolute paths, or set PATH explicitly in the crontab.
21. What does */15 mean in a cron minute field?
Show answer
Every 15 minutes (at :00, :15, :30, :45). */N means "every N units."
22. How do you prevent two cron job instances from running simultaneously?
Show answer
Use a lock file: flock -n /tmp/myjob.lock /path/to/script.sh — if the lock is held, the new instance exits immediately. Or use exec 9>/tmp/lock; flock -n 9 || exit 0 inside the script.
Networking & APIs¶
23. What does curl -sf do?
Show answer
-s silent (no progress bar), -f fail with non-zero exit code on HTTP errors (4xx/5xx). Together they make curl suitable for use in scripts where you detect failure by exit code.
24. How do you safely pass an API token to curl?
Show answer
Use the Authorization header: curl -H "Authorization: Bearer $TOKEN" URL. Store the token in an environment variable, not hardcoded in the script or on the command line.
Best Practices¶
25. What is ShellCheck and why should you use it?
Show answer
A static analysis tool that catches quoting bugs, anti-patterns, portability issues, and hundreds of common mistakes in bash scripts. Running shellcheck script.sh before committing is the highest-leverage habit in shell scripting.
26. When should you stop writing bash and switch to Python?
Show answer
When: the script exceeds ~200 lines and is growing; you need complex data structures; you need proper unit tests; you're doing significant JSON/HTTP work; or the logic is complex enough that others need to understand and modify it. Bash glues tools together; Python handles logic.
27. What does local var; var=$(cmd) fix compared to local var=$(cmd)?
Show answer
local var=$(cmd) always returns 0 because local returns 0 regardless of the command's exit code — hiding failures. Separating the declaration from the assignment lets the assignment's exit code propagate.
Start from the beginning with week-01-review. See also top-50-questions.