Anatomy of a script: shebang, arguments and exit codes
Structure professional Bash scripts with portable shebangs, strict positional argument validation, standard stream error reporting, and POSIX exit codes.
Contentsand lesson path
On this page
- Why it matters
- The Shebang Mechanism: Portability Across Operating Systems
- Positional Arguments: Parsing, Quoting, and Array Expansion
- Exit Codes: Communicating Status to Schedulers and CI/CD
- Check your understanding
- Apply it
- Review prompt
Lessons of Scripting Basics
- Anatomy of a script: shebang, arguments and exit codes Concept · 15 min
- Control flow you will actually use: tests, case, loops, functions, read and command substitution Worked example · 25 min
- Quoting, strict mode, tracing with set -x and failing loudly Worked example · 20 min
- Lab: an idempotent backup job with logging and a schedule Lab · 30 min
- Beyond Bash: jq, yq and porting a script to Python Worked example · 25 min
- Check: review and repair a fragile script Knowledge check · 8 questions
What you will learn
- Write a Bash script that takes arguments, validates input, uses variables, conditionals, loops and functions, and returns meaningful exit codes.
Prerequisites: Linux CLI
01. Why it matters
Many scripts are not run by the person who wrote them. A scheduler, a CI runner or a teammate starts them, often on a different machine, and nobody watches the terminal. Three small parts of a script decide whether that goes well. The first line (the shebang) decides which program runs the file, so a wrong one makes the script fail before your first command. Argument checks decide what happens when someone calls the script the wrong way: a clear usage message, or a half-finished change. And the exit code is the answer the caller acts on: by convention 0 means success and any other value means something went wrong, and a CI pipeline or scheduler trusts that number.
This lesson covers those three parts. Get them right, and a script fails early with a clear message instead of quietly doing the wrong thing.
02. The Shebang Mechanism: Portability Across Operating Systems
Every executable script in a Unix environment begins with a magic two-byte character sequence: the shebang (#!, hex 0x23 0x21). When an unprivileged or privileged process calls the execve() system call pointing to an executable file, the Linux kernel inspects the first memory buffer of the binary header (traditionally defined in BINPRM_BUF_SIZE, typically the first 128 to 256 bytes). If these two magic bytes are present, kernel execution intercepts normal binary ELF loading, treats the remainder of the first line as an interpreter directive, and launches that specified interpreter binary, passing the path of the script itself as an execution argument.
Two distinct conventions exist for declaring shell interpreters in automation repositories:
- Hardcoded Binary Path (
#!/bin/bash): Assumes the Bash executable is located at/bin/bash. That holds on Debian, Ubuntu and the Red Hat family, but the script fails to start where Bash lives elsewhere, such as FreeBSD and OpenBSD (/usr/local/bin/bash, if installed) or NixOS. On macOS/bin/bashexists but is the old Bash 3.2, so the script runs without the newer Bash features even if Homebrew installed Bash 5 in/opt/homebrew/binor/usr/local/bin. - Environment Lookup (
#!/usr/bin/env bash): Uses theenvutility, which sits at/usr/bin/envon nearly every system (POSIX specifiesenvbut not its path), to search the$PATHdirectories and run whicheverbashappears first. This works across most distributions, container images and workstations without editing the script. The trade-off: the script runs whateverbashthe caller'sPATHselects, and on Linux you cannot portably pass extra interpreter options on the shebang line.
If a script has no shebang, the kernel refuses to execute it (execve() fails with ENOEXEC), and what happens next depends on the caller. Bash runs the file itself with Bash, so Bash syntax works in your terminal. sh runs it as a POSIX shell script, and programs that call execve() directly, such as Python's subprocess, fail with Exec format error. So a script without a shebang can work in your terminal and break in CI or cron. On modern Debian and Ubuntu systems, /bin/sh is a symlink to Dash—a lightweight POSIX shell designed for fast system boot sequences. Dash strictly disallows modern Bash syntax such as arrays, double brackets [[ ... ]], process substitution <(...), and associative maps, resulting in baffling syntax errors when your script runs in continuous integration.
Furthermore, scripts must possess the execute mode bit (chmod +x script.sh). Without the execute permission bit set on the inode, invoking ./script.sh fails immediately with Permission denied, even if the file is readable by the executing user account.
03. Positional Arguments: Parsing, Quoting, and Array Expansion
When a script is launched from a shell or automated workflow engine, the Linux kernel and shell populate a set of automatic positional parameters that provide access to CLI flags and operands:
$0: The invocation path or command name used to trigger the script itself.$1,$2, ...$9: Positional arguments 1 through 9. For the tenth argument and beyond, braces are strictly required (${10},${11}). Without enclosing braces,$10evaluates to$1followed by a literal string0.$#: The total count of positional arguments passed to the script during invocation.shift N: Drops the first N positional parameters (default 1). Aftershift, the old$2becomes$1, the old$3becomes$2, and$#drops by one. Runningshift 2is commonly employed after validating required positional parameters before processing remaining variable argument lists."$@"vs"$*": When enclosed in double quotes,"$@"expands to separate words ("$1""$2""$3"), preserving internal spaces in filenames without triggering word splitting. In contrast,"$*"concatenates all parameters into a single continuous string separated by the first character of$IFS(typically a space). When a script forwards its arguments to another command,"$@"is almost always the one you want.
Defensive engineering requires validating all positional inputs immediately before performing stateful system actions. If parameters are missing, invalid, or malformed, the script must emit an explicit usage synopsis to standard error (>&2) and terminate immediately with a non-zero exit status code so downstream automation pipelines fail cleanly.
#!/usr/bin/env bash
set -euo pipefail
# Define usage function printing to standard error
usage() {
echo "Usage: $0 <target_directory> <retention_days>" >&2
exit 2
}
# Enforce exact argument count
if [ "$#" -ne 2 ]; then
echo "Error: Exactly 2 arguments required, received $#" >&2
usage
fi
TARGET_DIR="$1"
RETENTION_DAYS="$2"
# Validate that first argument is an existing directory
if [ ! -d "${TARGET_DIR}" ]; then
echo "Error: directory '${TARGET_DIR}' does not exist" >&2
usage # a bad argument is a usage error: exit 2
fi
# Validate that second argument is a whole number (digits only)
if ! [[ "${RETENTION_DAYS}" =~ ^[0-9]+$ ]]; then
echo "Error: retention days must be a whole number" >&2
usage
fi
echo "Validated parameters: ${TARGET_DIR} (retention: ${RETENTION_DAYS}d)"
exit 004. Exit Codes: Communicating Status to Schedulers and CI/CD
Every command, subshell, and script in Unix terminates by returning an 8-bit unsigned integer exit status between 0 and 255, stored in the special shell variable $?. Because the exit status is an 8-bit value (the number modulo 256), exit 256 in Bash results in an exit code of 0, which reports success and hides the failure. Use integers between 1 and 255 for error conditions.
Standardized conventions govern exit status codes across the POSIX and Linux ecosystems:
0(Success): The command or script completed its execution without error.1(General Operational Error): Standard catch-all for runtime operational failures (missing files, network timeouts, unhandled errors).2(Misuse of Shell Builtins / CLI Syntax Error): By common convention (Bash builtins,grep, many GNU tools and Python'sargparse), command-line usage errors such as a missing argument or an unknown flag return exit code 2. POSIX does not require this for every utility.126(Cannot Execute): The shell found the command but could not execute it, for example because the file lacks the execute permission.127(Command Not Found): The requested binary or script was not found anywhere along the active directories specified in$PATH.128 + N(Fatal Signal Termination): If a process is killed by an unhandled signal N, the kernel reports "killed by signal N" to the parent, and shells and container runtimes turn that into exit code 128 + N. For example, termination bySIGKILL(signal 9) produces code137(128 + 9), while termination bySIGTERM(signal 15) produces code143(128 + 15).
Workflow engines such as GitHub Actions, GitLab CI and Jenkins read this number: by default a step that exits with 0 lets the pipeline continue, and a non-zero exit fails the step and skips the steps after it, unless the step is marked to tolerate failure (continue-on-error in GitHub Actions, allow_failure in GitLab CI). Kubernetes uses the exit code of a container, together with its restart policy, to decide whether to restart it and whether a Job succeeded.
05. Check your understanding
06. Apply it
Implement these script authoring rules across your automation codebase:
- Standardize on env Shebang: Start scripts with
#!/usr/bin/env bash, so they find Bash throughPATHon Linux containers, macOS workstations and BSD servers, where Bash lives in different places. - Brace Double-Digit Arguments: Always write
${10}and${11}when referencing positional parameters beyond the ninth index. - Route Errors to Stderr: Always direct error and usage notifications to standard error (
echo "Error: ..." >&2) so monitoring systems and pipelines can differentiate diagnostic output from data streams. - Exit with Meaningful Codes: Reserve
exit 0strictly for clean execution, useexit 2for invalid CLI usage, and useexit 1for runtime execution failures. - Never Exceed Exit Code 255: Remember that exit codes are 8-bit unsigned integers; exiting with 256 wraps back to 0, accidentally masking fatal failures.
07. Review prompt
Explain how the Linux kernel interprets the shebang line during an execve() system call. Contrast "$@" and "$*" when processing arguments with whitespace, explain why referencing $10 without curly braces produces bugs, and detail the formula used to calculate process exit codes when terminated by signals.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.