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.
env
Here's a small set of the results on my system.
COLORTERM=truecolorTERM=xterm-256colorHOME=/Users/christopherbiscardiTMPDIR=/var/folders/br/5cvw25pn6zjbn5nqhf0ptnx80000gn/T/USER=christopherbiscardiXPC_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.
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.
Typing env
every time we want to check an env var is a bit verbose, so we can use special syntax instead.
➜ echo $THINGsomething
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.
➜ $THINGzsh: command not found: something
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.
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!