21

I recently discovered /etc/environment, which seems a more standard way to setup simple environment variables than scripts, but I was wondering if there was a way to back-reference environment variables in the /etc/environment file.

That is, I have this:

JAVA_HOME="/tools/java"
GRAILS_HOME="/tools/grails"
GROOVY_HOME="/tools/groovy"
GRADLE_HOME="/tools/gradle"
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"

If I try to add $JAVA_HOME/bin to the PATH definition, however, I get $JAVA_HOME/bin, and not the interpolated variable. To remedy this, I'm creating environment.sh in profile.d to add the /bin entries to the path, but this seems sloppy and disorganized.

Is there a way to backreference the environment variables in /etc/environment?

2 Answers2

14

The /etc/environment file is read by the pam_env PAM module. It only supports simple key-value pairs, with no substitution on the right-hand side.

If you want to build the value with substitutions or other shell expansions, you need to go through a shell. /etc/profile (or a file in /etc/profile.d) is the right place for these. This is the traditional place (/etc/environment is a relatively recent innovation, in the history of unix systems), and there's certainly nothing sloppy about using it. The main benefit of /etc/environment is that it allows environment variables to be set even with login methods that do not involve a shell or for users who use a non-Bourne shell, but these are not common in practice.

3

The Ubuntu documentation makes this seem impossible. BUT, there is an answer.

ANSWER: Create persistent, system wide environment variables in /etc/.bashrc

JAVA_HOME="/tools/java"
...
PATH="$JAVA_HOME:$PATH"  

Details:
Here are some more details from the Environment Variables documentation.
The official recommendation is to use /etc/environment, as you have tried. The problem is this file is not a script file. In other words, you cannot use variables in variable declarations.

The documentation continues with 2 other "Not Recommended" files
/etc/profile and /etc/bash.bashrc.

/etc/profile "does little more than invoke the /etc/bash.bashrc file". So instead choose

/etc/bash.bashrc because "Ubuntu is configured by default to execute this file whenever a user enters a shell or the desktop environment."

csi
  • 369