0
0
Linux CLIscripting~5 mins

Environment variables in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Environment variables store information that programs and scripts use to work properly. They help keep settings like paths and user preferences outside the code, making it easier to change behavior without editing scripts.
When you want to set a temporary value for a program to use during its run.
When you need to share configuration settings like database addresses or API keys across multiple scripts.
When you want to check what settings or paths are currently active in your shell.
When you want to make a variable available to all programs started from your shell.
When you want to customize your command prompt or other shell behaviors.
Commands
This command sets an environment variable named MY_VAR with the value HelloWorld and makes it available to all child processes started from this shell.
Terminal
export MY_VAR="HelloWorld"
Expected OutputExpected
No output (command runs silently)
This command prints the value of the environment variable MY_VAR to the terminal, showing what is currently stored.
Terminal
echo $MY_VAR
Expected OutputExpected
HelloWorld
This command lists all environment variables and filters the output to show only the variable MY_VAR, confirming it is set.
Terminal
env | grep MY_VAR
Expected OutputExpected
MY_VAR=HelloWorld
| grep MY_VAR - Filters the list to show only lines containing MY_VAR
This command removes the environment variable MY_VAR from the current shell session, so it is no longer available.
Terminal
unset MY_VAR
Expected OutputExpected
No output (command runs silently)
After unsetting, this command tries to print MY_VAR again, showing that it no longer has a value.
Terminal
echo $MY_VAR
Expected OutputExpected
Key Concept

If you remember nothing else from this pattern, remember: environment variables store settings outside your scripts so you can change behavior without editing code.

Common Mistakes
Setting a variable without export, like MY_VAR="HelloWorld"
The variable is only available in the current shell and not to programs or scripts started from it.
Use export MY_VAR="HelloWorld" to make it available to child processes.
Trying to access a variable without the $ sign, like echo MY_VAR
This prints the literal text MY_VAR instead of the variable's value.
Use echo $MY_VAR to print the value stored in the variable.
Expecting environment variables to persist after closing the terminal.
Variables set in a shell session are lost when the session ends.
Add export commands to shell startup files like ~/.bashrc to make them permanent.
Summary
Use export to create environment variables accessible to programs and scripts.
Use echo with $ to see the value of an environment variable.
Use unset to remove an environment variable from the current session.