Setting Environment Vars
Using profile.d for loading environment variables
I typically use profile.d for loading Environment Variables, there are other methods but I find this easier to maintain.
Steps
-
Use
echoto output theexportcommand, then redirect (>>) the output to a file in theprofile.ddirectory:sudo sh -c 'echo "export {YOUR_VARIABLE_NAME}={your-variable-value}" >> /etc/profile.d/{your-variable-name}.sh'- For the curious, here's how that breaks down:
Command Explanation sudoSubstitute User Do (previously "Superuser Do") - run command as a user with privileges, defaults to 'super user' shIn a shell (command interpreter) -cUse commands from the command_string (the next part, between 'and')echoOutput a line of text (the part between "and")exportSet the export attribute for variables >> /etc/profile.d/{your-variable-name}.shAppend Redirected Output ( >>) to the specified file (/etc/profile.d/{your-variable-name}.sh)
- For the curious, here's how that breaks down:
-
Use
chmod +xto mark the new file as executable:~ chmod +x /etc/profile.d/{your-variable-name}.sh -
Use
sourceto load the/etc/profile.d/{your-variable-name}.shfile into the current shell (this saves us from having to logout and back in):~ source /etc/profile.d/{your-variable-name}.sh -
Test that the variable is loaded by echoing it:
~ echo ${YOUR_VARIABLE_NAME}- You'll get a reply of {your-variable-value}
Example
In this example I create a new shell file in profile.d that exports an Environment Variable with the name TEST_API_KEY and value mykeyishere. I then make it executable, use source to load it, then echo it to make sure it's properly set.
~ sudo sh -c 'echo "export TEST_API_KEY=mykeyishere" >> /etc/profile.d/test-key.sh'
[sudo] password for user: _
~ sudo chmod +x /etc/profile.d/test-key.sh
~ source /etc/profile.d/test-key.sh
~ echo $TEST_API_KEY
mykeyishere
~_