A collection of computer systems and programming tips that you may find useful.
Brought to you by Craic Computing LLC, a bioinformatics consulting company.

Thursday, October 21, 2010

Setting Environment Variables for Sudo on Mac OS X

On Mac OS X you typically set up Unix environment variables in your ~/.bashrc or ~/.bash_profile files. To perform actions that need Root privileges you use 'sudo' instead of 'su'.

But when you 'sudo' a command your environment does not pick up your entire user environment and can cause problems in some cases.

To illustrate the issue, compare the output of these two commands in a Terminal (Unix shell):
$ printenv
$ sudo printenv

So how do you make a custom Environment variable visible to sudo? Rather than trying to modify system wide files like /etc/profile (which may not work anyway...) you want to modify the file /etc/sudoers.

Now, to modify this file you want to use the special command 'visudo', which as you can surmise, is a version of the editor 'vi'. Specifically it knows which file to edit and how to set the permissions on it. NOTE: If you don't know how to edit a file with 'vi' then learn the basics BEFORE you try the following steps!

$ sudo visudo
will bring the editor with the file opened. Look for this section:
# Defaults specification
Defaults env_reset
Defaults env_keep += "BLOCKSIZE"
Defaults env_keep += "COLORFGBG COLORTERM"

The env_keep lines indicate that the named environment variable should be made available to sudo. So you want to add your custom variable to this list by adding lines like this at the end of this section:
Defaults        env_keep += "APXS2"
And I would suggest adding a comment line (preceded by a # character) that makes it clear that this is a custom change. Save the file and look at the output of sudo printenv:
$ sudo printenv
Your custom environment variable should now be available.



Allan's said...

super tip dude!

S├ębastien Brault said...

Really good and elegant tip. Thanks a lot for sharing.

JGarrido said...

I had to use these steps to get Grails (version 2.x; 3.x seems fine) to see JAVA_HOME while running under sudo after an upgrade to OSX 10.11.1 El Capitan. Prior to that I was getting the following message when attempting to run grails as sudo:

grails: JAVA_HOME environment variable is not set

Archive of Tips