Managing Environment Variables in macOS Tahoe
Environment variables are dynamic values that affect the processes or programs on a computer. In macOS Tahoe, managing these variables is a key skill for terminal usage and scripting.
Viewing Environment Variables
To see a list of all current environment variables, use the printenv command in the terminal:
printenv
To view the value of a specific variable, use echo with the variable name prefixed by $:
echo $HOME
echo $USER
Setting Variables Temporarily
You can set a variable for the current terminal session using the export command. This variable will disappear once you close the terminal window.
export MY_VAR="Hello World"
echo $MY_VAR
Setting Variables Permanently
To make a variable persist across all terminal sessions, you need to add it to your Zsh configuration file (.zshrc).
- Open your
.zshrcfile (see Advanced Zsh Configuration in macOS Tahoe for details on editing this file). - Add the export line to the bottom of the file:
export API_KEY="123456789"
- Save the file and reload the configuration:
source ~/.zshrc
The PATH Variable
The most commonly modified environment variable is PATH. It tells the shell where to look for executable commands.
To add a new directory to your PATH (for example, a custom bin folder in your home directory), add this to your .zshrc:
export PATH="$HOME/bin:$PATH"
This appends your custom folder to the existing path, ensuring you can run scripts located there from anywhere.
Project-Specific Variables with .env
For development projects, it is common practice to store environment variables in a file named .env within the project root. This keeps configuration separate from code.
A typical .env file looks like this:
zsh +DB_HOST=localhost +DB_USER=root +API_SECRET=mysecretkey
To load these variables into your current shell session, you can use the following command:
zsh +export $(grep -v '^#' .env | xargs)
Note: Always add .env to your .gitignore file to prevent secrets from being committed to version control (see Managing Git Repositories on macOS Tahoe).