Top 10 Bash (Shell) scenario questions
Try each one yourself first, then open the model answer.
1. A script deletes the wrong files when a name contains spaces. Why?
Show answerHide answer
Unquoted variables are split into words and expanded as patterns. Quote them, as in "$file", and use arrays for lists.
2. A script continues after a command fails. How do you stop it?
Show answerHide answer
Use set -euo pipefail with care, and check important commands explicitly, since set -e has exceptions.
3. rm -rf "$DIR/" is dangerous if DIR is empty. How do you protect it?
Show answerHide answer
Fail when the variable is unset or empty, for example with ${DIR:?}, and verify the path before deleting.
4. Variables set inside a while loop fed by a pipe are lost. Why?
Show answerHide answer
Each part of a pipeline runs in a subshell. Feed the loop with a redirect or process substitution instead.
5. A cron job works in your terminal but not on schedule. What do you check?
Show answerHide answer
Cron has a minimal environment. Use full paths, set required variables, set the working directory and capture output to a log.
6. Temporary files are left behind when a script is interrupted. How do you clean up?
Show answerHide answer
Create them with mktemp and register a trap on EXIT that removes them.
7. Two copies of a backup script run at once and corrupt data. What do you add?
Show answerHide answer
A lock, for example with flock, so only one instance runs.
8. A script must process every file, including odd names. What is robust?
Show answerHide answer
Use find with -print0 and read with a null delimiter, or a glob loop with quoting.
9. A password appears in the process list. How should secrets be passed?
Show answerHide answer
Avoid command line arguments. Use protected files, standard input or a secrets manager, and keep secrets out of logs.
10. How would you debug a script that behaves differently on another server?
Show answerHide answer
Run with set -x, check the shebang and shell version, compare tool versions and PATH, and lint with ShellCheck.
