How to use direnv to create environment variables in ubuntu or MAC
Introduction: Problem with Environment variablesEnvironment variables are very important for setting up important variables that you don’t want to share in code. In my project, I have to set up some important variable that I require all over my project for the development. For example database names, email passwords, private keys and all other such things.
2. Setting environment variables without direnv
3. Install direnv in Ubuntu or MAC
4. Adding startup script in bashrc/ zshrc
Setting environment variables without direnv
$ export DB_USER=root $ export DB_PASSWORD=ranvir
import os DB_USER = os.environ['DB_USER'] DB_PASSWORD = os.environ['DB_PASSWORD']
Install direnv in Ubuntu or MACDirenv is an open-source project used for proper setting of environment variables. The idea behind this is that you set up all your variables in a single file called
.envrcand the environment will be created as soon as you enter the directory in which
.envrcfile is present. For installing
direnvin ubuntu apply the following command:
$ sudo apt-get install direnv
brew install direnv
Adding startup script in bashrc/ zshrcAfter this, you have to add the following line at the end of the
eval "$(direnv hook bash)"
zshas I do, you will have to add the following to
eval "$(direnv hook zsh)"
.envrcis present. Now go to a directory where you want to launch the environment variables. As long as you stay in that directory the value of environment variables will not change. Use the following commands to create a file
$ touch .envrc
export DB_NAME=abc export DB_USER=root
direnv: error .envrc is blocked. Run `direnv allow` to approve its content
$ direnv allow
direnv: loading .envrc direnv: export +DB_NAME ...
Did you enjoy reading or think it can be improved? Don’t forget to leave your thoughts in the comments section below! If you liked this article, please share it with your friends, and read a few more!