What are environment variables?
When a program runs, it receives information from the environment in which it is running. This environment information is passed implicitly via environment variables. These values are for example the locale system, terminal type, etc.
They are dynamically named values in the operating system, which affects the behaviors of the programs that consume it. They are stored in a key-value "list".
All values of environment variables are nonzero strings.
Generally, we save settings on these variables, both from the user logged in to the system, and system-wide . Here are some environment variables that are configured on my system:
"EDITOR"=>"vim",
"HOME"=>"/Users/vnbrs"
"LANG"=>"en_US.UTF-8"
"PAGER"=>"less"
"PWD"=>"/Users/vnbrs"
"SHELL"=>"/bin/zsh"
"SSH_KEY_PATH"=>"~/.ssh/rsa_id"
"USER"=>"vnbrs"
These settings can be retrieved by system processes. Subprocesses inherit environment variables from the parent process.
Do all languages have the same?
It is not that languages have, but processes. The languages of communication implementations with the APIs of the operating system to query them. An example with Python:
# test.py
import os
os.environ
And we execute in the shell:
$ python test.py
# => { 'COLORTERM': 'truecolor', 'PAGER': 'less', ... }
Most UNIX shells allow you to inject environment variables per program via the command line, see:
$ MINHA_VARIAVEL=meu_valor python test.py
# => { 'MINHA_VARIAVEL': 'meu_valor', 'COLORTERM': 'truecolor', 'PAGER': 'less', ... }
Note that this environment variable is only available for this process, in the python
case.
When should I use them?
Keys and Passwords
There are several uses of environment variables. A frequent use is to store keys and passwords, although there are better methods. Instead of having multiple constants in your application to save API keys, database passwords, and these things, why not put them in environment variables?
The development settings:
# development.env
MYSQL_HOST=0.0.0.0
MYSQL_USER=admin
MYSQL_PASSWORD=admin
GITHUB_API_KEY=test
STACKOVERFLOW_API_KEY=test
TRAVIS_CI_API_KEY=test
Production settings (dummy):
# production.env
MYSQL_HOST=172.28.281.1
MYSQL_USER=ncuabs9123h
MYSQL_PASSWORD=asduUG&*@!Y*#BSDbis
GITHUB_API_KEY=HASDb9IHU1u2h9
STACKOVERFLOW_API_KEY=oaishdBHSDP(*IH
TRAVIS_CI_API_KEY=ASIJPNDUQH*(@#audsibu
These variables can be loaded dynamically into the application, depending on the environment. Thus, you can hide the keys, not needing to share with those who do not compete this information.
System Settings
The operating system and some applications use the environment variables to locate. If you are developing in Java, you should know JAVA_HOME
. This is how programs know where Java is installed.
For those who "live" on the terminal you know that cd ~
will take you to the root of your disk. But where does it take this configuration from? It is the environment variable HOME
. In my case:
HOME=/Users/vnbrs