Use it when a variable is empty, has the wrong value, or is not seen by a script or program.
Variables
Shell variables hold strings (name=value, no spaces around =) and are read with $name or ${name}. export makes them environment variables for child processes; local limits them to a function.
1. declare -p name — set, exported, with what value?
2. Assignment failing → spaces around =?
3. Not seen by a child → export name.
4. Lost after a pipe or subshell → restructure.
5. Quote every use.
assignment → stored in the shell → optionally exported → expanded where used
For Shell & Bash → Variables, continue with the first unproven Topic check: Identify variable scope/attributes and whether the consumer is current shell, function, subshell or external process. If that boundary is healthy, advance to the adjacent check: Inspect value and argument boundaries safely, including empty/unset/whitespace/wildcard content. Preserve the same host/time/identity scope and rerun the original workload before accepting recovery.
Continue only after interpreting the current observation.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 Operational evidence path Verify boundary
assignment/source → shell variable table + scope/attributes → parameter expansion → optional export environment → fork/exec child → target process value/use → workload outcome
Healthy evidence: scope, value, attributes and export state are known, the intended consumer sees the exact value and persistence is verified in a fresh context when required.
Step 2 Verification and output interpretation Verify boundary
Existing fast checks for this Topic. - Identify variable scope/attributes and whether the consumer is current shell, function, subshell or external process.
- Inspect value and argument boundaries safely, including empty/unset/whitespace/wildcard content.
- Verify export state and the actual environment visible to the target process.
- For persistent configuration, edit the responsible startup/service/config source and create a fresh process/session to verify it.
Verification chain. assignment/source → shell variable table + scope/attributes → parameter expansion → optional export environment → fork/exec child → target process value/use → workload outcome
Step 3 Commands Verify boundary
name=web ; echo "$name"
declare -p name
export name
Step 4 Failure modes and next checks Narrow the fault
Suspicious evidence: a local value is mistaken for exported/persistent configuration, unset/empty semantics differ, or array/word splitting changes argument boundaries.
Step 5 Common mistakes Narrow the fault
- Spaces around
=. - Expecting non-exported variables in child processes.
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.
No spaces around =. Always quote when reading: "$name". Use ${name:-default} for defaults and ${name:?msg} to fail when unset. Variables set in a pipeline's subshell or a child script do not come back to the parent.
bash -x script.sh— trace each expanded commandbash -n script.sh— syntax check onlyshellcheck script.sh— common bugs and quoting problemsecho $?— exit code of the last command
ReferenceWhat it is1 section · depth on demand
Core model
Distinguish shell-local variables from exported environment, function-local variables, readonly/integer/array attributes and special parameters. Inspect values using quoting-safe representations, and trace export/inheritance at exec boundaries rather than assuming assignment changed persistent configuration.
ReferenceImportant terms & boundaries5 sections · depth on demand
What this shows and what it does not
Variable verification distinguishes current-shell binding, exported process environment and persistent source; seeing a value in one shell shows none of the others automatically.
In depth
Shell variables and parameter expansion
Bash variables hold strings, and also indexed or associative arrays. Parameter expansion can supply defaults, check for missing values and change the text without external tools. The bash(1) manual page documents the forms:
| Form | Result |
|---|---|
${v:-word} | word if v is unset or empty; v unchanged |
${v:=word} | As above, and also assigns word to v |
${v:?message} | Error (and exit, in scripts) if v is unset or empty |
${v:+word} | word only if v is set and non-empty |
${#v} | Length of the value |
${v#pat} / ${v##pat} | Remove the shortest / longest matching prefix |
${v%pat} / ${v%%pat} | Remove the shortest / longest matching suffix |
${v/pat/str} / ${v//pat/str} | Replace the first / every match |
${v^^} / ${v,,} | Upper / lower case |
+= appends to a value, and declare -n creates a reference to another variable.
Shell variables and environment variables
| Shell variable | Environment variable | |
|---|---|---|
| Created with | name=value | export name=value |
| Visible to child processes | No | Yes |
| List | set | env, printenv |
| For one command only | — | NAME=value command |
Common patterns
| Task | Expansion |
|---|---|
| File name without directory | ${path##*/} |
| Directory part | ${path%/*} |
| Change an extension | ${file%.log}.gz |
| A required argument in a script | : "${1:?usage: $0 <host>}" |
| A configurable default | port="${PORT:-8080}" |
host$ path=/var/log/nginx/access.log.1
host$ echo "${path##*/}" "${path%/*}" "${path%.1}"
access.log.1 /var/log/nginx /var/log/nginx/access.log
host$ echo "${HOSTNAME,,}" "${#path}"
srv1 27
host$ unset PORT; echo "${PORT:-8080}"
8080
host$ declare -a hosts=(srv1 srv2 srv3); echo "${#hosts[@]} ${hosts[1]}"
3 srv2
host$ declare -A owner=([nginx]=web [postgres]=db); echo "${owner[postgres]}"
db
host$ bash -c 'echo "${DEPLOY_ENV:?not set}"'
bash: line 1: DEPLOY_ENV: not set
Naming
Use lowercase names for your own script variables. Uppercase names are conventional for environment variables, and choosing lowercase avoids accidentally overwriting PATH, HOME or USER.
Documented example, not captured output.
How it works at runtime
Variables is part of Shell & Bash → Variables. Bash Variables are shell-name/value bindings distinct from exported environment variables; scope, attributes, arrays, positional parameters and expansion rules determine what child processes and functions actually observe.
Topic-specific state model. Bash Variables are shell-name/value bindings distinct from exported environment variables; scope, attributes, arrays, positional parameters and expansion rules determine what child processes and functions actually observe.
Interpretation rule. - Shell variable set ≠ child process receives it unless exported or included in an environment assignment.
- exported environment ≠ future login sessions receive it persistently.
- Unset variable ≠ empty variable in strict/default-value logic.
- Array variable ≠ scalar-safe expansion; ${a[*]} and ${a[@]} differ especially when quoted.
Quick reference
Bash variables:
name=web01 # no spaces around =
readonly BASE=/opt/app
local tmp # inside functions
export PATH="$BASE/bin:$PATH"
echo "${name}-backup"
echo "${port:-8080}" # default if unset/empty
: "${DB_HOST:?DB_HOST must be set}" # abort if missing
echo "${#name}" # length
echo "${file##*/}" "${file%.*}" # basename, strip extension
Special variables: $0 script, $1…$9 args, $# count, "$@" all args (quoted, preserves arguments), $? exit status, $$ PID, $! last background PID.
Limits and how it fails
Primary failure point. Variable verification distinguishes current-shell binding, exported process environment and persistent source; seeing a value in one shell shows none of the others automatically.
ReferenceConfiguration & state1 section · depth on demand
Configuration, persistence and lifecycle
Distribution/platform context. Environment Variables in Linux Fundamentals owns process-environment concept; .bashrc/.profile own common persistence/startup sources; this Topic owns Bash variable semantics.
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 Shell & Bash → Variables. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://www.gnu.org/software/bash/manual/bash.html · confidence 94%What changed and what may be affected
Recent technical edits are separated from ordinary page timestamps. Relationship impact is advisory: it identifies nearby canonical references to review, not automatic breakage.
Terms & aliases
Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.
Quick lookup tables
Variables operational reference
Topic-specific lookup boundaries, proof limits and next-step Evidence for Variables.
| Lookup boundary | Topic-specific reference | Operational use |
|---|---|---|
| Scope / effective state | Bash Variables are shell-name/value bindings distinct from exported environment variables; scope, attributes, arrays, positional parameters and expansion rules determine what child processes and functions actually observe. | Establish exactly what this Topic owns before crossing into another subsystem. |
| Fast verification | Pin host/distribution + shell/version/mode → identify cwd/mount namespace + input/path/stream → preserve quoting/expansion and final argv → map fd/pipeline/process boundaries → inspect object/variable/status/signal state → make one minimal reversible change → read back effective state → repeat original consumer/script/workload test. | Use the shortest evidence path first; a fast check is a boundary test, not blanket proof. |
| Verification chain | assignment/source → shell variable table + scope/attributes → parameter expansion → optional export environment → fork/exec child → target process value/use → workload outcome | Trace requested/configured state through effective state to the observed workload result. |
| Failure boundary | Variable verification distinguishes current-shell binding, exported process environment and persistent source; seeing a value in one shell proves none of the others automatically. | Stop broad troubleshooting at the first boundary that is not supported by evidence. |
| Positive evidence | Correlated Linux file/text/shell evidence can establish this proof path: assignment/source → shell variable table + scope/attributes → parameter expansion → optional export environment → fork/exec child → target process value/use → workload outcome | Use this observation only for the specific claim it actually supports. |
| Evidence limit | It does not independently prove behavior outside the captured host, shell/session, cwd/namespace, input, process, filesystem, locale, time or workload scope. Variable verification distinguishes current-shell binding, exported process environment and persistent source; seeing a value in one shell proves none of the others automatically. | Do not promote a local success signal into end-to-end or adjacent-dependency proof. |
| Next troubleshooting check | Continue from the first unproven boundary: capture the exact shell-delivered argv/streams or resolved object, verify the effective target state, change only the demonstrated cause, then repeat the original consumer/script/workload and adjacent regression checks. | Continue to the next unresolved boundary while preserving the original test condition. |
Variables · operational reference
Compact Linux state, persistence, verification and boundary reference for fast lookup.
| Reference boundary | Variables |
|---|---|
| Topic path | Shell & Bash → Variables |
| Runtime state | Bash Variables are shell-name/value bindings distinct from exported environment variables; scope, attributes, arrays, positional parameters and expansion rules determine what child processes and functions actually observe. |
| Fast checks | - Identify variable scope/attributes and whether the consumer is current shell, function, subshell or external process. - Inspect value and argument boundaries safely, including empty/unset/whitespace/wildcard content. - Verify export state and the actual environment visible to the target process. - For persistent configuration, edit the owning startup/service/config source and create a fresh process/session to verify it. |
| Verification chain | assignment/source → shell variable table + scope/attributes → parameter expansion → optional export environment → fork/exec child → target process value/use → workload outcome Boundary chain: local authoritative state → adjacent dependency → effective/programmed state → original workload/request → return/regression → explicit Evidence boundary. Boundary chain: local authoritative state → adjacent dependency → effective/programmed state → original workload/request → return path or regression → explicit Evidence boundary. |
| Failure boundary | Variable verification distinguishes current-shell binding, exported process environment and persistent source; seeing a value in one shell proves none of the others automatically. Boundary chain: process/context → userspace configuration → kernel subsystem/resource → device/network/filesystem dependency → effective state → original workload. |
| Persistence rule | Prove which configuration source owns the state, then prove that the running consumer loaded or generated the intended state. |