Shell – How to set global environment variables at boot through a script, and have them available for an application that runs before login

bootenvironment-variablesrhelshell-script

I have a service that runs at boot, and in that service it calls a bash script in the background that exports some environment variables. The problem I'm having is that those environment variables are not being sent to the parent of the background process so as soon as my script is done executing, they are gone.

In addition, after the script is run the service then calls another script that starts an application that I have. This application needs access to those environment variables.

The RHEL system I run it on is meant to never be logged in to by the user, it only boots up and starts the application. I know that environment variables for a parent process/shell can't really be set by a child background process shell though.

I need a way to do this through a script that gets called by my service (not necessarily in the background though), not by adding them in my service (which didn't work either for me) and not by storing them in an /etc/environment or .profile or anything such as that.

In my service I tried adding the environment variables (not what I want to do though):

    export TEST=192.168.1.1

I also tried this in my service:

    TEST=192.168.1.1
    export TEST=${TEST}

I tried changing how my service calls the bash script:

    /bin/asdf/script &

I also tried sourcing the script so that it runs in the same shell (which I got from this):

    . ./bin/asdf/script
    #I'm very confused why this didn't work

I also found this which looked interesting but it didn't really pan out in my case.

Best Answer

You can try putting a script to gather the variables in /etc/profile.d/

Example:

/etc/profile.d/somescript.sh

#!/bin/bash
TEST=$(cat /var/somefile)
export $TEST

/etc/profile does a call that will run any script in /etc/profile.d/, and this applies to all users on the system including root.

Related Question