How to Set an Environment Variable
Set an environment variable for the current terminal session, verify it, and make it permanent in your shell profile on macOS, Linux, and Windows.
A program needs a value like an API key from the environment. Set it for the current terminal, confirm it is there, then make it permanent if you need it in every session.
Set the variable in the current shell
export API_KEY=abc123
No spaces around =. If the value contains spaces or special characters, quote it: export API_KEY="abc 123".
Windows Command Prompt:
set API_KEY=abc123
Windows PowerShell:
$env:API_KEY="abc123"
The variable exists only in this terminal window and in programs started from it. Open a new window and it is gone.
Read it back
echo $API_KEY
abc123
Command Prompt uses echo %API_KEY% and PowerShell uses echo $env:API_KEY. To see every variable that is set, run env (or set on Windows).
Set it for a single command
Put the assignment in front of the command, without export:
API_KEY=abc123 python3 app.py
The variable is visible to that program only and does not linger in your shell.
Make it permanent on macOS or Linux
Add the export line to your shell's startup file. macOS uses zsh by default, so the file is ~/.zshrc. Most Linux distributions use bash, so it is ~/.bashrc. Run echo $SHELL if unsure.
echo 'export API_KEY=abc123' >> ~/.zshrc
New terminals read the file automatically. To apply it to the terminal you already have open:
source ~/.zshrc
Make it permanent on Windows
Search the Start menu for "Edit environment variables for your account", click New, and enter the name and value. Or from a terminal:
setx API_KEY abc123
setx saves the variable for future sessions but does not change the current window. Open a new terminal to see it.
If the variable belongs to one project. Put it in a .env file in the project folder (API_KEY=abc123, one per line) and load it with a library such as python-dotenv, or with Node's built-in node --env-file=.env. This keeps project settings out of your global shell profile.
If the value is a secret. Add .env to .gitignore before the first commit. A key that has been pushed, even briefly, should be treated as leaked and rotated.
More Coding how-tos
- How to Add a .gitignore File
- How to Check Which Node.js Version Is Installed
- How to Check Which Python Version Is Installed
- How to Clone a Git Repository
- How to Connect to a Server with SSH
- How to Create a New Git Branch
- How to Create a Python Virtual Environment
- How to Delete a Git Branch
- How to Install Node.js with nvm
- How to Install Python Packages with pip
- How to Make a Script Executable in the Terminal
- How to Print Hello World in JavaScript
- How to Print Hello World in Python
- How to Read a JSON File in Python
- How to Resolve a Merge Conflict in Git
- How to Run a Local Web Server in One Command
- How to Stash Changes in Git
- How to Undo the Last Git Commit
- How to Write Your First Bash Script