Pcornel
Browse topics
Options
Recent
Favorites
Automation · Technical reference

Variables · Bash Automation

Direct answer

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.

When to use this

Use this when assigning, quoting and using variables and arrays in Bash scripts.

First 30 seconds

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.

Operational verification

value → variable → quoted use

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
GNU Bash 5.3/current
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformGNU Bash 5.3/current · Automation implementations are tool and platform specific. Use the adjacent Domain for the technology being automated and this Domain for automation behavior.
Scope / prerequisiteUse this when assigning, quoting and using variables and arrays in Bash scripts.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

3 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

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 references

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.

observation · 1
Key points
  • Assign without spaces: name=value.
  • Read with "$name" to keep spaces intact.
  • Use arrays for lists and readonly for constants.
Key checks
  • declare -p VAR — show variable
  • shellcheck -i SC2086 script.sh — unquoted variables
  • readonly 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
ScopeRule
Shell variableVisible in the current shell
export VARPassed to child processes
local in functionsLimited 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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.
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
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor docGNU Bash 5.3/current 5.3/current

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%
Embedded reference data

Quick lookup tables

Bash Automation → Variables · operational reference

Context-specific ownership, verification, output and failure-boundary lookup for Bash Automation → Variables.

LayerBash Automation → Variables operational reference
Context identityGNU Bash 5.3/current + exact revision/input/target identity
Persistent intentVersioned contract/configuration with explicit ownership and prerequisites
VerificationValidate inputs/read current state → exercise bounded operation → independent target read-back
Output contractPreserve structured status/IDs/properties before human formatting
Failure boundarySeparate source/input/engine/controller execution from downstream target outcome
Depth when you need it

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.

Confirmation

Confirm action

Continue?