🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Environment Variables

An environment variable is a variable shared with the programs a script runs. The export command marks a variable for that sharing.

An exported variable shows in env

The export line marks CITY for sharing. Searching the env output finds the line CITY=Paris.

export CITY="Paris"
env | grep "^CITY="

A plain variable stays hidden

Both counts search env output for a line starting with the name. The exported CITY scores one, and the plain LOCAL scores zero.

export CITY="Paris"
LOCAL="Rome"
env | grep -c "^CITY="
env | grep -c "^LOCAL="
echo "Only the exported one is shared"

Exporting more than one variable

Each export adds one more shared variable. Both new names appear in the env output.

export COLOR="green"
export SIZE="large"
env | grep "^COLOR="
env | grep "^SIZE="

Example

LOCAL="hidden"
export CITY="Paris"
export COURSE="Bash"
echo "Exported lines found:"
env | grep -c "^CITY="
env | grep -c "^COURSE="
echo "Local lines found:"
env | grep -c "^LOCAL="
echo "Sharing check complete"

Key points

  • A plain variable lives only inside the current script.
  • Use export NAME=value to share a variable with programs the script runs.
  • The env command prints the environment it receives.
  • An exported variable appears in the env output.
  • A plain variable never appears in the env output.
  • Bash itself sets variables such as $HOME and $USER for each session.

In this example, the script sets one plain variable and exports two others. The counts show both exported names in the env output, one line each. The plain LOCAL name scores zero, so it stays private to the script.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the export command do to a variable?