Welcome to new things

[Technical] [Electronic work] [Gadget] [Game] memo writing

How to automatically change environment variables for each directory in Linux

The Docker Compose project name is the name of the directory where the docker-compose.yaml file is located.

However, there are many cases where you may want to give a directory a different name. In such cases, you can specify the project name with the -p <project_name> option each time you execute the docker-compose command, or set the project name in the COMPOSE_PROJECT_NAME environment variable.

Since docker-compose is a command that is often entered by hand, it is time-consuming to specify the project name for each command execution, so it is set in the environment variable.

However, it is tedious to re-set environment variables every time you switch projects, and in fact, I often forget to do so.

In such cases, the tool "direnv", which automatically changes environment variables for each directory, is extremely useful!

direnv.net

treatment

Place the following environment variable settings in the directory where you want to set them, under the file name .envrc.

export COMPOSE_PROJECT_NAME="test-project"

Then, when you move under that directory, the environment variables written in the file are automatically set!

Moreover, if you move out of that directory, the set environment variables are automatically deleted!

How to Install

Execute the following command to install

curl -sfL https://direnv.net/install.sh | bash

After that, put the following commands in .bashrc and so on, so that the commands will be invoked when the shell is executed.

eval "$(direnv hook bash)"

That's all.

bonus

It also works with the Node.js version management tool nvm to automatically switch Node.js versions.

Impressions, etc.

I had an image that environment variables are not often changed once they are set, but I have seen many cases like docker-compose where the settings are changed by environment variables.

Until now, I had to place a script to change environment variables and run it every time, but to be honest, it was a hassle.

That's when I saw "direnv" used in the Google Cloud Platform CLI documentation.

It is so convenient that I wish Linux would include it as a standard feature.

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com