Use this when assigning, quoting and using variables and arrays in Bash scripts.
Variables · Bash Automation
Bash variables are assigned without spaces (name=value) and read with "$name". They are untyped strings by default; use arrays for lists and declare -r for constants.
1. Always quote "$var".
2. Use ${var:-default} and ${var:?error}.
3. local in functions.
4. Uppercase for exported/env, lowercase for locals.
5. Arrays for lists.
value → variable → quoted use
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Verification path Verify boundary
Verify variables at the scope where the consumer sees them. declare -p name shows whether a Bash parameter exists and reveals attributes/array shape; printf '%q' exposes whitespace and metacharacters without relying on visual spacing; and env or a deliberately launched child process shows whether an exported value crosses the process boundary. Exercise unset, empty, whitespace-containing and delimiter-containing values because those are where unsafe expansions normally surface. For positional parameters, print the argument count and quote each argument separately rather than joining $*. If a command substitution supplies a value, verify both the substitution command's status and the resulting text before use. The final check should inspect the target resource or generated artifact that consumed the variable, so verification demonstrates the meaning of the input rather than merely that a shell variable existed.
Step 2 Common mistakes Narrow the fault
- Unquoted variables.
- Spaces around
=in assignments.
Step 3 Where it fails Narrow the fault
The key boundaries are shell scope, process environment, expansion, and consumer interpretation. A value can be correct in the parent shell yet absent from a child because it was not exported; correct as a scalar yet corrupted by unquoted splitting; present in a subshell yet unavailable after the subshell exits; or passed intact to a tool whose own parser interprets it differently. Shell options such as nounset change how missing parameters fail, while command substitutions introduce a second command-status boundary. Diagnose in that order: show definition/scope, show the expanded argv/environment, then show how the downstream tool or API interpreted the value. Do not 'fix' a variable by globally exporting it or weakening strict mode unless the missing boundary is actually demonstrated. Re-run from a clean non-interactive shell to ensure the result is not inherited from stale session state.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
- Assign without spaces: name=value.
- Read with "$name" to keep spaces intact.
- Use arrays for lists and readonly for constants.
declare -p VAR— show variableshellcheck -i SC2086 script.sh— unquoted variablesreadonly CONST=value— constants
ReferenceWhy it matters1 section · depth on demand
In depth
Bash variables are untyped strings (with optional integer and array support), set without spaces around = and expanded with $. Quoting rules decide whether spaces and wildcards in values are preserved.
name="core switch"
echo "$name" # preserved
echo $name # split into two words
hosts=(sw01 sw02 sw03); echo "${hosts[@]}"
count=$((count + 1))
backup_dir=${BACKUP_DIR:-/backup} # default value
: "${API_TOKEN:?API_TOKEN must be set}" # fail if unset
| Scope | Rule |
|---|---|
| Shell variable | Visible in the current shell |
export VAR | Passed to child processes |
local in functions | Limited to the function |
ReferenceImportant terms & boundaries1 section · depth on demand
Mechanics
A Bash variable is a shell parameter with a name; it is not automatically an environment variable and it is not a typed configuration object. Assignment creates or changes shell state, export marks a parameter for inclusion in the environment of subsequently executed child processes, local/declare can constrain scope or attributes inside functions, and positional/special parameters ($1, $@, $?, $$, and others) are populated by the shell runtime. Expansion is a separate phase: ${name}, default/alternate/error operators, substring and pattern removal, arrays, command substitution, arithmetic expansion, and indirect expansion can all transform what the command finally receives. The difference between unset and set-to-empty is especially important in automation because ${x:-default} and ${x-default} intentionally behave differently. Subshells and pipelines may copy state without propagating later assignments back to the parent shell.
ReferenceConfiguration & state1 section · depth on demand
Lifecycle
Treat external inputs, derived working variables, secrets, and exported environment as different classes. Validate externally supplied values before deriving commands from them; use readonly for invariants once computed; limit export to values a child process actually needs; and use function-local variables to prevent accidental cross-step coupling. Avoid depending on interactive shell profiles because schedulers, CI runners, cron and SSH command mode may initialize a different environment. Prefer explicit defaults and failure-on-missing forms over ambiguous empty strings, and keep secret values out of tracing and ordinary diagnostic output. When arrays are required, preserve element boundaries with "${array[@]}" instead of collapsing them into a single string. Persist durable configuration in a reviewed file, secret store, inventory or workflow input contract—not in a long-lived shell process whose state is invisible to the next run.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Bash Automation > Variables. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html · confidence 94%Quick lookup tables
Bash Automation → Variables · operational reference
Context-specific ownership, verification, output and failure-boundary lookup for Bash Automation → Variables.
| Layer | Bash Automation → Variables operational reference |
|---|---|
| Context identity | GNU Bash 5.3/current + exact revision/input/target identity |
| Persistent intent | Versioned contract/configuration with explicit ownership and prerequisites |
| Verification | Validate inputs/read current state → exercise bounded operation → independent target read-back |
| Output contract | Preserve structured status/IDs/properties before human formatting |
| Failure boundary | Separate source/input/engine/controller execution from downstream target outcome |
Deep reference
Healthy vs suspicious evidence
Output interpretation
Variable output must preserve both value and shape. echo $var is a poor diagnostic because unquoted expansion is followed by word splitting and glob expansion, and echo itself has implementation-dependent option/escape behavior. Prefer printf, declare -p, or structured serialization for machine comparisons. Distinguish an unset parameter from an empty string, a scalar from an array, and a shell-only variable from an exported environment entry. For secrets, log only presence, source, identifier or hash/fingerprint where appropriate—never the raw value. When a variable is passed to another process, the most useful evidence is often the child's interpreted configuration or target read-back rather than the parent's printed assignment. Capturing these distinctions prevents a common false diagnosis where a variable 'looks right' in one shell but is split, defaulted, not exported, or overwritten before the real consumer uses it.