How to Set an Environment Variable
current stable releases (Python 3.12+, Node 22, Git 2.4x) on Mac, Linux, and Windows · Last checked · Suggest an edit
https://instructions.wiki/coding/set-an-environment-variable
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.