johndhpark
4/4/2019 - 2:59 AM

Setting up environment variables with various shells

Setting up environment variables with various shells

What the hell are environment variables?

They're just variables you set on your system that various programs/processes can read. A fairly standard example in javascript circles would be setting your NODE_ENV variable to "production" or "development", altering how node code is executed on your system (for example showing more debug messaging when in development).

With most shells there's a way to set them for the current session, and a way to set them for all sessions. The following is meant to be a guide on how to set env vars in the various shells.

Bash (The default shell on OSX)

Setting for the session:

$ export MY_VAR="some value"
$ echo $MY_VAR
some value

To persist this, you need to edit the .bash_profile file inside your home directory to include the following line:

# other stuff
export MY_VAR="some value"

You then need to make sure your system loads in the new variables. You can do this using the source command:

$ echo $MY_VAR
->
$ source ~/.bash_profile
$ echo $MY_VAR
-> some value

zsh

Pretty much exactly the same as above, but you'll want to edit your .zshrc file.

fish shell

Fish has quite different syntax to bash. The following is equivalent to the above bash example:

$ set -x SECRET "butts"
$ echo $SECRET
-> butts

To persist the env var, edit ~/.config/fish/config.fish to include the following line:

set -x SECRET "butts"

(the -x option exports the variable so it can be used by programs other than the shell).