Pcornel
Browse topics
Options
Recent
Favorites
Linux · Technical reference

Variables

Direct answer

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.

When to use this

Use it when a variable is empty, has the wrong value, or is not seen by a script or program.

First 30 seconds

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.

Operational verification

assignment → stored in the shell → optionally exported → expanded where used

Evidence · next step

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
Platform / version applicability
linux
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.

Platformlinux
Scope / prerequisiteUse it when a variable is empty, has the wrong value, or is not seen by a script or program.
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.

5 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 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 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

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.

Key checks
  • bash -x script.sh — trace each expanded command
  • bash -n script.sh — syntax check only
  • shellcheck script.sh — common bugs and quoting problems
  • echo $? — 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:

FormResult
${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 variableEnvironment variable
Created withname=valueexport name=value
Visible to child processesNoYes
Listsetenv, printenv
For one command only—NAME=value command

Common patterns

TaskExpansion
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 defaultport="${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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

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
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 doclinux current

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%
Technical changelog & impact

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.

Related reference impactReview these references after material technical changes when their shared boundary is affected.
Terminology layer

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.

Aliases that resolve here
bash variablesshell variables exportbash arrays variablesenvironment vs shell variable
Embedded reference data

Quick lookup tables

Variables operational reference

Topic-specific lookup boundaries, proof limits and next-step Evidence for Variables.

Lookup boundaryTopic-specific referenceOperational use
Scope / effective stateBash 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 verificationPin 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 chainassignment/source → shell variable table + scope/attributes → parameter expansion → optional export environment → fork/exec child → target process value/use → workload outcomeTrace requested/configured state through effective state to the observed workload result.
Failure boundaryVariable 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 evidenceCorrelated 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 outcomeUse this observation only for the specific claim it actually supports.
Evidence limitIt 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 checkContinue 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 boundaryVariables
Topic pathShell & Bash → Variables
Runtime stateBash 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 chainassignment/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 boundaryVariable 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 ruleProve which configuration source owns the state, then prove that the running consumer loaded or generated the intended state.
Confirmation

Confirm action

Continue?