An environment variable is a user-definable value that can affect the way running processes will behave on a computer.
Environment variables are useful because they allow configuration settings to be adjusted without changing the application code for each environment (such as staging, production, or development).
Say you’re coding on your local machine. You don’t want to accidentally hit the live database. Instead, you can set up a different database for development which is separate from your production setup. And use environment variables to switch between different configurations. This way, your local development stays separate, and there’s no risk of messing up live data.
In Linux, an environment variable can be set using the export keyword. This makes the variable available to any process started from the current shell.
export NAME=RABI
It is conventional to use uppercase letters for environment variable names so they can be easily distinguished from other types of variables within the code.
Consider the following JavaScript code snippet contained within a test.js
file:
console.log('Process', process.env.NAME);
To illustrate the effect of setting an environment variable, I conducted an experiment with two terminal sessions. In the first terminal, I set the NAME
variable using the export
command shown above. In the second terminal, I did not set the NAME
variable. When I executed test.js
in the first terminal, the output correctly displayed the value of NAME
. However, in the second terminal where the variable was not set, no value was printed.
This shows how environment variables are specific to the shell session in which they are defined. If they are not defined in a particular session, any processes or scripts running in that session will not have access to those variables.
To persist environment variables beyond the current session so they’re not lost when the terminal is closed, you can define them in shell configuration files. If you’re using bash, adding export NAME=value
to the end of your ~/.bashrc
or ~/.bash_profile
file will get the job done.
Some Good Reads: