70 %

Toast is in Beta!Learn more →

Chris Biscardi

What are environment variables?

What is an environment variable?

Environment variables (also know as env vars) are used heavily in CLI programs, servers, and more. They are variables set in the environment that your program is running in. Often these are set for you. Running env on a unix system (Macs, Linux, WSL, etc) will get you a list of all env vars currently set in your shell.

dump-env-vars.sh
shell
env

Here's a small set of the results on my system.

shell
COLORTERM=truecolor
TERM=xterm-256color
HOME=/Users/christopherbiscardi
TMPDIR=/var/folders/br/5cvw25pn6zjbn5nqhf0ptnx80000gn/T/
USER=christopherbiscardi
XPC_SERVICE_NAME=0

These env vars specifically probably don't mean anything to you or to our program, but we can set our own as well.

shell
export THING=something

If we run env now, THING shows up in the results. This variable will only exist for the terminal session you're in right now so if you start a new terminal THING won't be there.

Dollar signs

Typing env every time we want to check an env var is a bit verbose, so we can use special syntax instead.

shell
echo $THING
something

If we use the echo command, we can display the value of the THING env var using $THING syntax. Interestingly if we use $THING on its own, our terminal will try to execute the value inside as a program.

shell
$THING
zsh: command not found: something

Inline env vars

You can also set environment variables inline before executing a program. You might use this to set your editor to VS Code when committing in git.

shell
EDITOR="code -w" git commit

git uses the special EDITOR command to determine which editor to open, so you could use this to try out vim, emacs, nano, sublime, or any other editor!