How to set the environment variables to be used by the service running on Linux machine

Viewed 1087

The my-service that is running on the Linux machine needs to be supplied with the ENV_VAR environment variable. It works if I declare this variable in the etc/environment file with:

vim /etc/environment then adding an extra line:

ENV_VAR="My Value"

And finally reloading it with:

source /etc/environment

I then can re-start the my-service with:

sudo service my-service stop sudo service my-service start

I wonder if I could avoid declaring ENV_VAR variable in the etc/environment file. Is there a way to declare the environment variable to be seen by the service using any other approach?

2 Answers

So if you want to add an Environment Variable you could do a number of things:

  1. Edit /etc/enviroment (All Users)
  2. Edit /etc/profile (All Users)
  3. Edit ~/.bashrc (Just You)

Editing any of the files above will ensure that any time you startup your machine, your environment will have access to those variables.

You could also edit my-service or a file that my-service includes (as suggested by Cyrus). This means that if you have write access to the source code for the my-service program or a file that my-service includes (calls before it's own execution), you could add a line to that file.

You also don't even have to edit a file! Whenever you launch a terminal you can make live changes to the environment simply by entering the text you would have added to one of the files mentioned above as a command. This environment change will be just like the ~/.bashrc change, in that it will only work for the current user. If you plan to sudo <command>, you will have to first sudo su to switch to the super-user user, and then change the environment.

Weather you are editing a file or entering a command, I suggest using the following line of code. The export command will ensure that environment variable is accessible by my-service.

export ENV_VAR=value

Related question

Is there a way to declare the environment variable to be seen by the service using any other approach?

If your system uses systemd to manage the service, from systemd.exec documentation section "Environment" you can add to your service file:

Environment="ENV_VAR=My Value"
Related