How to Use Environment Variables in Bash: Syntax and Examples
In Bash, you set an environment variable using
export VAR_NAME=value and access it with $VAR_NAME. These variables store data that scripts and commands can use during execution.Syntax
To create or update an environment variable, use export VAR_NAME=value. To read the variable, use $VAR_NAME in your script or command.
- export: Makes the variable available to child processes.
- VAR_NAME: The name of your variable (uppercase by convention).
- value: The data you want to store.
- $VAR_NAME: Accesses the value stored in the variable.
bash
export MY_VAR="Hello World" echo $MY_VAR
Output
Hello World
Example
This example shows how to set an environment variable and then use it in a script to print a greeting message.
bash
#!/bin/bash export GREETING="Hello" export NAME="Alice" echo "$GREETING, $NAME!"
Output
Hello, Alice!
Common Pitfalls
Common mistakes include not exporting the variable, which means child processes won't see it, or forgetting to use $ when accessing the variable.
Also, avoid spaces around the = sign when assigning values.
bash
# Wrong: variable not exported, child processes can't access it
MY_VAR="No export"
echo $MY_VAR
# Right: export variable to make it available
export MY_VAR="Exported"
echo $MY_VAROutput
No export
Exported
Quick Reference
| Command | Description |
|---|---|
| export VAR=value | Set and export an environment variable |
| echo $VAR | Access and print the variable's value |
| unset VAR | Remove the variable from environment |
| VAR=value command | Set variable only for a single command execution |
Key Takeaways
Use 'export VAR=value' to create environment variables accessible to child processes.
Access variables with '$VAR' to use their stored values in scripts or commands.
Always avoid spaces around '=' when assigning variables in Bash.
Export variables if you want them available to other programs or scripts.
Use 'unset VAR' to remove environment variables when no longer needed.