The Analogy: The Duty Board in a Haulage Dispatch Office
A haulage depot runs its day off a duty board on the dispatch office wall. It holds the figures that matter this morning: which depot is loading, which route is running, the day's mileage limit, the fuel card series in use, the temperature ceiling for the chilled trailers. Everyone in the office reads the board, and the clerk writes on it as the day changes. The board belongs to the office. It is the office's working memory, and nothing outside that room can see it.
When a driver is sent out, the clerk prints a run sheet. Crucially, the run sheet does not reproduce the whole board. Each box on the board has a small tick-box in its corner marked "carry forward", and only the ticked boxes get printed onto the sheet. The depot code is ticked because every driver needs it. The internal figure for how many pallets are still unallocated is not, because it is nobody's business out on the road. So the driver leaves with a subset of the board, printed on paper, and that paper is theirs.
What the driver does with that paper does not come back. They can cross out the mileage limit and write a new one, annotate the route, scribble a different depot code in the margin. The board in the office is completely unaffected, because the sheet was a photocopy taken at the moment of printing and there was never a wire running back to the wall. When the driver returns, the sheet goes in the day file and the annotations go nowhere. If dispatch wants a figure updated, the driver has to tell the clerk, and the clerk has to write on the board.
The failure mode is the box that was never ticked. Somebody tells a driver "the concrete grade is on the board", and it is -- but the carry-forward box beside it is empty, so the run sheet arrives with that field blank. The driver does not stop and telephone the office. They turn the pad over, read the pre-printed house default on the reverse, and use that. The load goes out with the wrong grade, and no refusal slip is generated anywhere, because from every individual's point of view the process worked. The second failure is the mirror of it: two drivers are told to "update the board with your actual mileage", which cannot happen, and the depot spends a month believing the board updates itself.
Syntax or Core Structure
An assignment in bash has no spaces around the equals sign. That is not a style rule; name = value is parsed as the command name with the arguments = and value, and you get "command not found".
#!/usr/bin/env bash
DEPOT=ashford
export ROUTE=north
printf 'parent: DEPOT=[%s] ROUTE=[%s]\n' "$DEPOT" "$ROUTE"
bash child.sh
printf 'parent: DEPOT=[%s] ROUTE=[%s]\n' "$DEPOT" "$ROUTE"
printf '%s\n' '-- with a one-command assignment prefix --'
ROUTE=south bash child.sh
printf 'parent: ROUTE=[%s]\n' "$ROUTE"
printf '%s\n' '-- after exporting DEPOT as well --'
export DEPOT
bash child.sh
child.sh reports what reached it and then tries to change both values:
#!/usr/bin/env bash
printf 'child : DEPOT=[%s] ROUTE=[%s]\n' "${DEPOT-unset}" "${ROUTE-unset}"
DEPOT=child-wrote-this
ROUTE=child-wrote-this
printf 'child : changed both to [%s] [%s]\n' "$DEPOT" "$ROUTE"
Output:
parent: DEPOT=[ashford] ROUTE=[north]
child : DEPOT=[unset] ROUTE=[north]
child : changed both to [child-wrote-this] [child-wrote-this]
parent: DEPOT=[ashford] ROUTE=[north]
-- with a one-command assignment prefix --
child : DEPOT=[unset] ROUTE=[south]
child : changed both to [child-wrote-this] [child-wrote-this]
parent: ROUTE=[north]
-- after exporting DEPOT as well --
child : DEPOT=[ashford] ROUTE=[north]
child : changed both to [child-wrote-this] [child-wrote-this]
Every rule in this lesson is visible in those eleven lines. DEPOT is on the board but not ticked, so the child reports it as unset -- not empty, genuinely absent. ROUTE is exported, so the child sees north. The child then reassigns both and prints its own new values, and the parent's next line shows both original values completely unchanged, because the child was given a photocopy. ROUTE=south bash child.sh puts a value into one command's environment only, and the parent's ROUTE is still north on the line after. Finally, export DEPOT ticks the box, and the next child sees ashford.
Note that printf '%s\n' '-- with ...' passes the dashes as an argument rather than as the format string. printf would otherwise read a leading -- as its own option terminator and complain, which is a small trap worth meeting once.
Technical Depth: The Board, the Tick-Box and the Photocopy
Three kinds of name
| Kind | Where the value lives | Reaches a child process |
|---|---|---|
| shell variable | in this shell process only | no |
| environment variable | in this shell, and copied into every child at the moment it starts | yes |
| special parameter | maintained by the shell itself, such as $?, $#, $$ and $! | no, and most cannot be assigned at all |
There is no third state and no partial visibility. A name is either ticked for carry-forward or it is not, and export is the tick. env, printenv and export -p all list the ticked names; plain set lists everything on the board, which is why its output is enormous.
Export is a copy taken at the moment of the fork
This is the single most misunderstood point. export does not create a shared value. It marks the name so that when a child is created, that name and its value at that instant are written into the child's environment. Change the value in the parent afterwards and children started later see the new value; children already running see the old one. Change it in the child and the parent sees nothing, ever. There is no mechanism in the process model for a child to write into its parent's memory, which is why every "make my script set a variable in my shell" question is really a request to source the script instead of running it.
The assignment prefix, and its exact scope
ROUTE=south bash child.sh puts ROUTE into the environment of that one command without touching the current shell at all. It is the cleanest way to run something with one setting changed, and it composes: LC_ALL=C TZ=UTC sort file sets two. The one surprise is that a prefix on a function call or a builtin can leak into the current shell in some modes, so keep prefixes for external commands, where the behaviour is unambiguous.
declare, and the attributes worth knowing
| Flag | What it does to the name |
|---|---|
-i | integer attribute; the right-hand side of every later assignment is evaluated as arithmetic |
-r | readonly; any further assignment fails with status 1 and cannot be undone, not even by unset |
-a | indexed array |
-A | associative array, which must be declared before first use |
-x | identical to export |
-u and -l | force the value to upper or lower case on every assignment |
-n | nameref: the variable becomes an alias for whatever name its value holds |
-g | inside a function, create the variable globally rather than locally |
-p | print the declaration of a name rather than using it, which is the fastest way to see a variable's attributes |
#!/usr/bin/env bash
declare -i n=5
n=n+3
printf 'declare -i : n=%s\n' "$n"
m=5
m=m+3
printf 'plain : m=%s\n' "$m"
declare -r LIMIT=42
if ( LIMIT=43 ) 2>/dev/null; then
printf 'declare -r : subshell assignment reported success\n'
else
printf 'declare -r : assignment refused, status %d\n' "$?"
fi
printf 'declare -r : LIMIT is still %s\n' "$LIMIT"
declare -u UP=hello
declare -l LO=WORLD
printf 'declare -u : %s\n' "$UP"
printf 'declare -l : %s\n' "$LO"
declare -a list=(one two three)
printf 'declare -a : %d elements, second is %s\n' "${#list[@]}" "${list[1]}"
declare -A rate=([north]=12 [south]=15)
printf 'declare -A : north %d, south %d\n' "${rate[north]}" "${rate[south]}"
Output:
declare -i : n=8
plain : m=m+3
declare -r : assignment refused, status 1
declare -r : LIMIT is still 42
declare -u : HELLO
declare -l : world
declare -a : 3 elements, second is two
declare -A : north 12, south 15
The first two lines are the whole point of -i. With the integer attribute, n=n+3 is arithmetic and gives 8; without it, the same text is a plain string assignment and m literally contains the three characters m+3. The readonly test runs in a subshell purely so the shell's complaint can be discarded and the status inspected: the message goes to standard error, the status is 1, and the value is untouched.
Unset is not empty
Bash distinguishes "this name has no value" from "this name's value is the empty string", and the two are told apart by whether a colon appears in the expansion:
| Expansion | when the name is unset | when the name is set but empty |
|---|---|---|
${a-D} | D | the empty string |
${a:-D} | D | D |
${a+X} | the empty string | X |
${a:+X} | the empty string | the empty string |
${a?message} | prints the message and exits a non-interactive shell | the empty string |
#!/usr/bin/env bash
unset a
b=
for v in a b; do
printf '%-5s dash-default=[%s] colon-dash=[%s] is-set=%s\n' \
"\$$v" "${!v-DEFAULT}" "${!v:-DEFAULT}" "$([ -v "$v" ] && echo yes || echo no)"
done
Output:
$a dash-default=[DEFAULT] colon-dash=[DEFAULT] is-set=no
$b dash-default=[] colon-dash=[DEFAULT] is-set=yes
${!v} is indirect expansion: it takes the value of v as a name and expands that. The -v test asks the question directly and is the readable way to check for existence rather than for emptiness. The distinction matters most in configuration code, where "the user explicitly set this to nothing" and "the user said nothing" are different instructions.
Names that already mean something
| Name | What bash is already using it for |
|---|---|
PATH | where commands are found; clobbering it breaks every command after that line |
IFS | word splitting, everywhere, for the rest of the script |
HOME | tilde expansion, and the default location for a great many tools |
PWD and OLDPWD | maintained by cd; assigning them makes cd - lie |
REPLY | the destination read and select use when you give them no variable name |
RANDOM, SECONDS, LINENO | generated on each reference; a plain assignment destroys the feature for the rest of the run |
BASH_SOURCE, FUNCNAME, BASH_VERSINFO | arrays bash maintains for you |
OPTIND and OPTARG | getopts state, which is why a second option loop needs OPTIND=1 |
The convention that keeps you out of trouble is lower case or mixed case for your own script-local names, and upper case reserved for things you deliberately export. It is only a convention, but it makes an accidental collision with PATH or IFS visually obvious. What happens when you do collide is not subtle:
#!/usr/bin/env bash
( PATH=/nonexistent; ls /tmp >/dev/null 2>&1
printf 'inside subshell with broken PATH: %d\n' "$?" )
ls /tmp >/dev/null 2>&1
printf 'outside, PATH intact : %d\n' "$?"
Output:
inside subshell with broken PATH: 127
outside, PATH intact : 0
Status 127 from ls is the same "not found" you met with shebangs, arriving for a completely different reason. The parentheses are what saved the rest of the script: a subshell gets its own copy of everything, so the damage is discarded at the closing bracket.
Real World Example: Settings That Come From Four Places At Once
Every tool of any size ends up resolving each setting from four sources, in a fixed order of authority: the command line beats the environment, which beats a configuration file, which beats a built-in default. Getting that precedence right, and being able to show which source won, is most of what variables and export are for.
#!/usr/bin/env bash
set -u
DEPOT_DEFAULT=ashford
ROUTE_DEFAULT=north
LIMIT_DEFAULT=40
DROPS=4
cli_DEPOT= cli_ROUTE= cli_LIMIT=
for arg in "$@"; do
case $arg in
--depot=*) cli_DEPOT=${arg#*=} ;;
--route=*) cli_ROUTE=${arg#*=} ;;
--limit=*) cli_LIMIT=${arg#*=} ;;
*) printf 'runsheet: unknown option %s\n' "$arg" >&2; exit 2 ;;
esac
done
declare -A conf=()
while IFS= read -r line; do
case $line in ''|'#'*) continue ;; esac
key=${line%%=*}
val=${line#*=}
case $key in
DEPOT|ROUTE|LIMIT) conf[$key]=$val ;;
*) printf 'runsheet: ignoring unknown config key %s\n' "$key" >&2 ;;
esac
done < runsheet.conf
value= source=
resolve() {
local key=$1
local cliname=cli_$key
local envname=RUNSHEET_$key
local defname=${key}_DEFAULT
if [ -n "${!cliname}" ]; then value=${!cliname}; source='command line'
elif [ -n "${!envname-}" ]; then value=${!envname}; source=environment
elif [ -n "${conf[$key]-}" ]; then value=${conf[$key]}; source='config file'
else value=${!defname}; source='built-in default'
fi
}
printf '%-6s %-9s %s\n' KEY VALUE SOURCE
for key in DEPOT ROUTE LIMIT; do
resolve "$key"
printf '%-6s %-9s %s\n' "$key" "$value" "$source"
printf -v "final_$key" '%s' "$value"
done
printf 'allowance: %d km (%s km limit x %d drops)\n' \
"$(( final_LIMIT * DROPS ))" "$final_LIMIT" "$DROPS"
The configuration file beside it holds a comment, DEPOT=dover, LIMIT=55 and a key the tool does not recognise, GRADE=C30. A driver script runs it four times to make the precedence visible:
#!/usr/bin/env bash
printf '%s\n' '== config file and built-in defaults only'
./runsheet.sh
printf '%s\n' '== RUNSHEET_ROUTE set but NOT exported'
RUNSHEET_ROUTE=east
./runsheet.sh
printf '%s\n' '== the same name exported'
export RUNSHEET_ROUTE
./runsheet.sh
printf '%s\n' '== command line beats everything'
./runsheet.sh --route=west --limit=60
Output: (standard output and standard error together)
== config file and built-in defaults only
runsheet: ignoring unknown config key GRADE
KEY VALUE SOURCE
DEPOT dover config file
ROUTE north built-in default
LIMIT 55 config file
allowance: 220 km (55 km limit x 4 drops)
== RUNSHEET_ROUTE set but NOT exported
runsheet: ignoring unknown config key GRADE
KEY VALUE SOURCE
DEPOT dover config file
ROUTE north built-in default
LIMIT 55 config file
allowance: 220 km (55 km limit x 4 drops)
== the same name exported
runsheet: ignoring unknown config key GRADE
KEY VALUE SOURCE
DEPOT dover config file
ROUTE east environment
LIMIT 55 config file
allowance: 220 km (55 km limit x 4 drops)
== command line beats everything
runsheet: ignoring unknown config key GRADE
KEY VALUE SOURCE
DEPOT dover config file
ROUTE west command line
LIMIT 60 command line
allowance: 240 km (60 km limit x 4 drops)
The second and third blocks are the lesson in miniature. They run the identical command with the identical variable set to the identical value, and they disagree, because between them sits one word: export. Without it RUNSHEET_ROUTE is a figure on the office board that was never ticked for carry-forward, so the child never sees it and falls back to its built-in north. With it, the same name is copied into the child's environment and east wins. Any time a script "ignores an environment variable you definitely set", this is the first thing to check.
The configuration file is read rather than executed, which is deliberate. key=${line%%=*} takes everything before the first equals sign and val=${line#*=} takes everything after it, so a line is data and only data. Unknown keys are reported and skipped rather than silently absorbed, which is why GRADE=C30 produces a warning on standard error in every run. This is the fix for the flaw in the previous lesson's tool, which sourced its config and therefore executed whatever was in it.
The arithmetic reconciles the run. Four drops at the resolved limit gives 220 kilometres while the config's 55 stands, and 240 in the last block where the command line raised the limit to 60, so the printed allowance changes only when the input that feeds it changes. printf -v "final_$key" writes into a variable whose name is built from the loop key, which is how the loop leaves three separate resolved values behind for the arithmetic to use; the names come from a fixed list in the for statement, never from user input, which is the condition that makes constructing a variable name from data acceptable.
The real design flaw is the emptiness test. Every level is checked with [ -n ... ], which asks "is this non-empty", not "was this set". So RUNSHEET_LIMIT= ./runsheet.sh -- an operator deliberately clearing the value -- prints LIMIT 55 config file, silently ignoring an explicit instruction, and there is no way for a caller to override a config setting back to empty. The correct test is [ -n "${!envname+set}" ], using the plus form from the table above. Two related weaknesses: nothing validates that LIMIT is a number, so RUNSHEET_LIMIT=abc gets as far as the arithmetic and dies with abc: unbound variable, an error message that names neither the setting nor the source it came from; and resolve returns its answer by writing two global variables called value and source rather than printing it, which works but means any caller that uses either of those names for its own purposes will be quietly overwritten.
Common Mistakes
- Putting spaces around the equals sign.
name = valueis three words, so bash tries to run a command calledname.name =valueandname= valuefail in their own distinct ways. The error message says "command not found", which sends people looking for a missing program rather than at the whitespace.
- Expecting a child process to change the parent's variable. A script you run cannot set a variable in your shell, and neither can the last stage of a pipeline, because each is a separate process working from a photocopy. If the value genuinely has to come back, either
sourcethe file or have the child print the value and capture it with$( ... ).
- Forgetting
exportand then blaming the child. The symptom is a tool that "ignores" a variable you can see withecho.echoreads the board; the child reads its run sheet. Check withprintenv NAME, which shows only the ticked names, rather than withecho "$NAME", which shows both kinds indistinguishably.
- Using a variable in the same command that assigns it. In
x=new printf '%s' "$x"the expansion of$xhappens while the command line is being built, before the prefix takes effect, so it prints the old value. Assignments in a prefix are visible to the command's environment, not to the command line's own expansions.
- Testing
-nor-zwhen the question is "was this set". Both tests treat unset and empty identically, so a deliberately empty value is indistinguishable from silence. Use[ -v name ]or[ -n "${name+set}" ]when the difference matters, which in configuration handling it usually does.
- Assigning to a name bash already owns.
PATH,IFS,HOME,REPLY,OPTINDand the generated variables likeRANDOMandSECONDSall have jobs. ClobberingRANDOMwith a plain assignment does not fail; it permanently replaces the generator with a fixed string for the rest of the run.
- Assuming variables inside a function are local. They are global by default. A function that sets
ias a loop counter will happily destroy the caller'si, and the bug appears in a loop several screens away.localon every variable a function introduces is not optional discipline; it is the only thing standing between you and action at a distance.
- Writing
export VAR=$(command)and thinking you checked the command. The status of that line is the status ofexport, which is 0 almost always, so a failing command substitution passes silently andVARis empty. Assign on one line, check the status, then export on another -- or at minimum use a plain assignment, which does report the substitution's status.
- Putting secrets in exported variables and forgetting who inherits them. Every child process, including ones you did not write and ones started much later, receives the whole environment. A token exported at the top of a script is handed to every tool the script calls. Pass secrets on standard input or through a file with tight permissions, and prefer an assignment prefix on the single command that needs it.
Best Practices
- Use lower case for your own names and upper case only for what you export. It is a convention rather than a rule, but it makes an accidental collision with
PATHorIFSvisible on the page instead of at three in the morning.
- Declare every function-local variable with
local. Include loop counters and temporaries. Combined withlocal -rfor values that should not change after they are computed, this turns a class of distant bugs into an immediate error.
- Prefer an assignment prefix over exporting for the whole script.
TZ=UTC dateandLC_ALL=C sort fileaffect exactly one command and cannot leak into anything else. Export only what genuinely has to reach many children.
- Distinguish unset from empty deliberately. Pick
${name-default}when an empty value is a legitimate choice and${name:-default}when it is not, and write down which you meant. Silently conflating them is the single most common configuration bug in shell tooling.
- Set the environment your script needs at the top, explicitly. Assign
PATH,LC_ALLandTZif their values change the output, rather than inheriting whatever the caller had. This is what makes a script produce the same result under your prompt, under cron and in CI.
- Use
declare -rfor constants anddeclare -ifor counters. The readonly attribute catches accidental reassignment at the point it happens, and the integer attribute meansn=n+1is arithmetic rather than string concatenation, which removes a whole family of quiet mistakes.
- Read configuration files instead of sourcing them. A loop with
key=${line%%=*}and a whitelist of recognised keys turns a config file into data. Sourcing turns it into code, and code in a file that operations staff can edit is a privilege escalation waiting to be noticed.
- Inspect with the right tool.
printenv NAMEfor what a child will see,declare -p NAMEfor the value plus its attributes,envorexport -pfor the whole exported set.echo "$NAME"answers none of those questions precisely.
Practice Exercises
- Draw the boundary yourself. Write a parent script that sets four variables, exports two of them, and calls a child that reports all four and then reassigns all four. Add a second call to the child after the parent changes one exported value. Predict all three blocks of output before running, then explain any line you got wrong.
- Build the precedence resolver. Write a script that resolves three settings from command line, environment, config file and built-in default, and prints which source won for each. Then make the empty case correct: arrange it so that setting an environment variable to the empty string overrides the config file with an empty value rather than being ignored, and prove it.
- Break the special names on purpose. In a subshell each time, assign to
PATH, thenIFS, thenRANDOM, and record what stops working in each case and how the failure presents itself. Note which of the three fails loudly and which fail silently.
- Catch a leaking function. Write a function that uses
i,tmpandcountwithoutlocal, call it from inside a loop that uses the same three names, and demonstrate the resulting wrong answer. Then addlocaland show the loop's result is correct. Finish by usingdeclare -pto display all three names' attributes before and after.