# Revision and Interview Questions — Bash / Shell Scripting

Source: https://www.skillbyai.com/en/bash/p-revision

> Recall Bash scripting concepts quickly for exams and interviews.

## Cheat sheet

**Basics**: `#!/usr/bin/env bash`, `chmod +x`, exit status 0 = success, `$?`, `exit N`; `/bin/sh` may be dash; macOS ships Bash 3.2. **Variables**: no spaces around `=`; `export` for children; `local` in functions; special `$0 $1 $# $@ $? $$ $!`. **Quoting**: double-quote every expansion (`"$var"`, `"$@"`, `"${arr[@]}"`); single quotes are literal. **Expansion**: `${var:-def}`, `${var:?msg}`, `${var#pre}`, `${var%suf}`, `${var//a/b}`, `${#var}`, `$(cmd)`, `$((math))`. **Tests**: `[[ ]]` for strings, patterns, regex; `(( ))` for numbers; file tests `-f -d -e -r -s`. **Flow**: `if`, `case`, `&&`/`||`; `for f in *.ext`, `while IFS= read -r line; do ...; done < file`, avoid `cat | while`. **Functions**: `"$@"`, `shift`, `return` for status, print for data. **Arrays**: indexed, associative (`declare -A`), `mapfile -t`. **I/O**: `>`, `>>`, `2>&1`, `&>`, `/dev/null`, here-docs, `<(cmd)`, `xargs -0`. **Robustness**: `set -Eeuo pipefail` and its caveats, `trap ... EXIT/ERR/INT`, `mktemp`, `${dir:?}` before `rm`, `flock`, atomic `mv`, ShellCheck, `bash -x`. **Automation**: cron's minimal environment, systemd timers.

## Common interview questions

Answer with a short example each time.

```text
1. What is the difference between "$@" and "$*"?
2. Why should you quote variable expansions? Give an example of what breaks.
3. [ ] vs [[ ]] vs (( )): when do you use each?
4. What does set -euo pipefail do, and what are its pitfalls?
5. How do you read a file line by line safely?
6. How do you redirect both stdout and stderr to a file?
7. How do you make sure temporary files are cleaned up?
8. How do you return a value from a function?
9. Why might a script work in your terminal but fail in cron?
10. When would you rewrite a Bash script in another language?
```

## Show the bug, then the fix

Interviewers love concrete examples: "`rm $file` breaks on 'my file.txt' because of word splitting; `rm -- "$file"` fixes it." A one-line bug and fix shows real experience.

**Quiz:** Which line correctly passes all of a script's arguments, unchanged, to another command?

- [ ] other_cmd $*
- [ ] other_cmd $@
- [ ] other_cmd "$*"
- [x] other_cmd "$@"

*Answer:* other_cmd "$@". "$@" expands each argument as its own word, preserving spaces inside arguments.
