Linux · Systems fluency

How do you write a reliable shell script?

MediumbashscriptingautomationUpdated Oct 2026
Quiz this track

Short answer

Use an explicit shebang, strict error handling, quoted expansions, functions, and clear exit codes. Validate inputs, use temporary files safely, and prefer purpose-built tools over fragile parsing.

A reliable script fails loudly and early. set -e, set -u, and pipefail catch many mistakes, but they are not a substitute for checking exit codes where a failure is expected or recoverable.

sh
#!/usr/bin/env bash
set -euo pipefail

main() {
  local target="$1"
  echo "deploying to $target"
}

main "$@"

Practices that prevent incidents

  • Quote variables unless word splitting is intentional
  • Use dollar-at in double quotes to forward arguments without mangling spaces
  • Use mktemp for temporary files and trap to clean them up
  • Check required commands with command -v before running
  • Run ShellCheck in CI to catch common bugs

Avoid parsing ls output and avoid assuming whitespace-free filenames. Use find with -print0 and read -d for safe iteration. Prefer a real programming language when the script grows complex data structures or error handling.

set -e has edge cases in conditions, pipelines, and subshells. Test the failure paths, not only the happy path, and make destructive actions require an explicit confirmation or dry-run flag.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What does set -euo pipefail do?
  2. 2Why is quoting variables important?
  3. 3How do you handle temporary files safely?
  4. 4When should you stop using shell and switch languages?

Say it in the interview

I start with a shebang and strict mode, then quote expansions and forward arguments with dollar-at. I validate inputs and use mktemp with a trap for cleanup. ShellCheck catches many subtle bugs. When a script needs complex data handling or rich error recovery, I switch to a real programming language instead of forcing shell.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Linux mock interview and get scored feedback on depth, clarity and confidence.