How to Set Environment Variable in Linux: Simple Steps
To set an environment variable in Linux temporarily, use
export VARIABLE_NAME=value in the terminal. For permanent settings, add the export command to your shell's configuration file like ~/.bashrc or ~/.profile.Syntax
Use the export command to set an environment variable in the current shell session. The syntax is:
export VARIABLE_NAME=value: Sets the variableVARIABLE_NAMEtovaluefor the current session.VARIABLE_NAME=value: Sets the variable only for the current command if used before a command.
bash
export VARIABLE_NAME=valueExample
This example shows how to set a temporary environment variable and check its value.
bash
export MY_VAR=hello
echo $MY_VAROutput
hello
Common Pitfalls
One common mistake is setting a variable without export, which makes it unavailable to child processes. Another is forgetting to reload the shell configuration file after adding variables for permanence.
bash
MY_VAR=hello echo $MY_VAR # Works in current shell bash -c 'echo $MY_VAR' # No output because MY_VAR is not exported # Correct way: export MY_VAR=hello bash -c 'echo $MY_VAR' # Outputs 'hello'
Output
hello
Quick Reference
| Action | Command | Description |
|---|---|---|
| Set temporary variable | export VAR=value | Available in current shell and child processes |
| Set variable for one command | VAR=value command | Only for that command execution |
| Make variable permanent | Add export VAR=value to ~/.bashrc | Loads on new shell sessions |
| Reload config file | source ~/.bashrc | Apply changes without logout |
Key Takeaways
Use
export VARIABLE_NAME=value to set environment variables for the current session.Add export commands to
~/.bashrc or ~/.profile to make variables permanent.Reload your shell config with
source ~/.bashrc after editing to apply changes immediately.Without
export, variables are not passed to child processes.Use
VAR=value command to set a variable only for a single command execution.