0
0
Linux-cliHow-ToBeginner · 3 min read

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 variable VARIABLE_NAME to value for the current session.
  • VARIABLE_NAME=value: Sets the variable only for the current command if used before a command.
bash
export VARIABLE_NAME=value
💻

Example

This example shows how to set a temporary environment variable and check its value.

bash
export MY_VAR=hello

echo $MY_VAR
Output
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

ActionCommandDescription
Set temporary variableexport VAR=valueAvailable in current shell and child processes
Set variable for one commandVAR=value commandOnly for that command execution
Make variable permanentAdd export VAR=value to ~/.bashrcLoads on new shell sessions
Reload config filesource ~/.bashrcApply 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.