100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Bash

Bash Script Structure and Shebangs

How to structure a production-quality Bash script, from the shebang line and strict-mode settings to functions, exit codes, and portability considerations.

Advanced FundamentalsIntermediate9 min readJul 10, 2026
Analogies

The Shebang Line and How Scripts Get Executed

The shebang (#!) on the first line of a script tells the kernel which interpreter to invoke; #!/bin/bash pins the script to Bash specifically, while #!/usr/bin/env bash searches $PATH for bash, which is more portable across systems like macOS or NixOS where bash may not live at /bin/bash. The shebang only has effect if the file has execute permission (chmod +x) and is invoked directly (./script.sh); running it as bash script.sh bypasses the shebang entirely and always uses the bash binary you invoked.

🏏

Cricket analogy: Naming a specific bowler for the first over versus just calling for 'a fast bowler' from whoever is warmed up is the difference between #!/bin/bash pinning an exact interpreter path and #!/usr/bin/env bash finding whichever bash is available on the field.

Strict Mode and Defensive Options

Production scripts commonly start with set -euo pipefail: -e exits immediately if any command returns non-zero, -u treats references to unset variables as errors, and pipefail makes a pipeline's exit status reflect the last command that failed rather than only the final command in the pipe. This combination, often called 'unofficial strict mode', catches silent failures early instead of letting a script limp along with corrupted state.

🏏

Cricket analogy: Playing under DRS with strict no-ball checks on every delivery catches infractions immediately rather than letting them slide, just as set -e stops a script the instant a command fails rather than continuing on a bad over.

bash
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

usage() {
  echo "Usage: $(basename "$0") <input-dir> <output-dir>" >&2
  exit 1
}

main() {
  local input_dir="${1:?input-dir required}"
  local output_dir="${2:?output-dir required}"

  [[ -d "$input_dir" ]] || { echo "Error: $input_dir not found" >&2; exit 2; }
  mkdir -p "$output_dir"

  for file in "$input_dir"/*.log; do
    cp "$file" "$output_dir/"
  done
}

[[ $# -eq 2 ]] || usage
main "$@"

Functions, main(), and Exit Codes

Well-structured scripts define reusable logic in functions declared before use, wrap the top-level flow in a main() function called with "$@" at the very end of the file (making the script easier to test and reason about top-down), and return meaningful exit codes via exit N — conventionally 0 for success, 1 for a general error, 2 for misuse of shell built-ins/bad arguments, and higher numbers for specific documented failure modes that calling scripts or CI pipelines can branch on.

🏏

Cricket analogy: A team's playing eleven is organized into specialist roles (openers, all-rounders, death-over specialists) called upon at the right moment, just as a script's functions are organized units called from main() at the right point in execution.

Exit code conventions worth following: 0 = success, 1 = general error, 2 = misuse/bad arguments, 126 = command found but not executable, 127 = command not found, 128+N = terminated by signal N (e.g., 130 = SIGINT/Ctrl-C). Documenting your script's custom exit codes in a header comment or --help output makes it far easier for other scripts and CI systems to branch on failure reasons.

Portability and Shellcheck

Bashisms like [[ ]], arrays, and process substitution <(...) are not POSIX sh features, so a script relying on them must use a #!/bin/bash or #!/usr/bin/env bash shebang rather than #!/bin/sh, since on Debian-based systems /bin/sh is dash, which will fail or silently misbehave on Bash-only syntax. Running scripts through ShellCheck (shellcheck script.sh) as part of CI catches unquoted variables, unreachable code, and dozens of other classic mistakes before they reach production.

🏏

Cricket analogy: Playing a T20-specific slog-sweep shot in a Test match against a well-set field is a format mismatch, just as using Bash-only [[ ]] syntax under a #!/bin/sh (dash) shebang is a syntax-versus-interpreter mismatch.

  • #!/usr/bin/env bash is generally more portable than #!/bin/bash because it searches $PATH rather than assuming a fixed location.
  • The shebang only takes effect when the script has execute permission and is invoked directly (./script.sh).
  • set -euo pipefail (unofficial strict mode) causes scripts to fail fast on errors, unset variables, and failed pipeline stages.
  • Structure scripts with functions declared first and a main() function called with "$@" at the bottom for readability and testability.
  • Follow exit code conventions (0 success, 1 general error, 2 misuse, 126/127 for exec issues, 128+N for signals) and document custom codes.
  • Bash-only syntax like [[ ]] and arrays will break under #!/bin/sh on systems where sh is dash — use a bash shebang if you rely on them.
  • Run scripts through ShellCheck in CI to catch quoting, scoping, and portability bugs before they reach production.

Practice what you learned

Was this page helpful?

Topics covered

#Bash#AdvancedBashScriptingStudyNotes#DevOps#BashScriptStructureAndShebangs#Script#Structure#Shebangs#Shebang#StudyNotes#SkillVeris