How to Export Variable in Bash: Simple Guide
In bash, you export a variable using the
export command, like export VAR=value. This makes the variable available to any child processes started from the current shell.Syntax
The basic syntax to export a variable in bash is:
export VARIABLE_NAME=value: Sets and exports the variable in one step.export VARIABLE_NAME: Exports an already set variable.
Exporting a variable means it will be passed to child processes.
bash
export VARIABLE_NAME=value # or VARIABLE_NAME=value export VARIABLE_NAME
Example
This example shows how to export a variable and access it in a child process (a subshell).
bash
export MY_VAR="Hello World" echo "Parent shell: $MY_VAR" bash -c 'echo "Child shell: $MY_VAR"'
Output
Parent shell: Hello World
Child shell: Hello World
Common Pitfalls
One common mistake is setting a variable without exporting it, so child processes cannot see it.
Wrong way:
MY_VAR="Hello" bash -c 'echo "$MY_VAR"' # Outputs nothing
Right way:
export MY_VAR="Hello" bash -c 'echo "$MY_VAR"' # Outputs Hello
Quick Reference
| Command | Description |
|---|---|
| export VAR=value | Set and export variable in one step |
| VAR=value; export VAR | Set variable then export it |
| export VAR | Export an existing variable |
| unset VAR | Remove variable from environment |
Key Takeaways
Use
export VAR=value to set and export a variable in one command.Exported variables are available to child processes started from the shell.
Setting a variable without export keeps it local to the current shell only.
You can export an existing variable by running
export VAR.Use
unset VAR to remove a variable from the environment.