Skip to content
Environment Variables & Expansion
step 1/5

Reading — step 1 of 5

Read

~1 min readBuilt-ins & Variables

Environment Variables & Expansion

The shell maintains two sets of variables:

Shell variables — local to the shell process. name=value sets one. Environment variables — same, but ALSO inherited by child processes. export name=value makes a shell variable an environment variable.

Variable expansion happens during command line processing, AFTER tokenization but BEFORE execution:

SyntaxMeaning
$VARvalue of VAR (empty if unset)
${VAR}same, with explicit boundaries
${VAR:-default}use VAR or "default" if VAR is unset/empty
${VAR:=default}use VAR or assign+use "default"
${VAR:?error message}error out if VAR is unset/empty
${#VAR}length of VAR's value
$0 $1 ... $9positional arguments (script args, function args)
$@ $*all positional args
$?exit status of last command
$$shell's own PID

Special rule: variables are expanded inside "..." but NOT inside '...'.

Order of expansion is fixed: tilde -> variable -> command -> arithmetic -> word splitting -> globbing.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…