Monday, October 11, 2021

Setting environment variables on Ubuntu

Example

export JAVA_HOME=/usr/local/jdk-15.0.2
export PATH="$PATH:$JAVA_HOME/bin"

Without the export command, the variables are just shell variables; it means they aren't recognized by the sub processes or programs that start from the shell. 


Login shell vs non-login shell

A shell in Unix is a program that provides command line interface for OS and user interaction. The Terminal application is just an emulator or GUI for a shell.

Login shell - ssh is an example.

Non-login shell - the Terminal application by default starts a non-login shell but inherits the user environment variablbes loaded from the graphical login shell.


Session-wide environment variables

It affects only specific user.

The ~/.profile file

Each user has its own .profile file. It gets executed by the DisplayManager when the desktop session loads as well as by the login shell when one logs in from the textual console.

The ~/.profile file is not automatically executed by just restarting the Terminal application because it's not a login shell. For the file modification to take effect, logout the user account and login again.


System-wide environment variables

It affects the system as a whole (rather than just a specific user). 

The /etc/environment file

The downside is variables do not expand. In the example below, the PATH variable would end up containing only "/bin" because $PATH and $JAVA_HOME don't get replaced with their values.

export JAVA_HOME=/usr/local/jdk-15.0.2
export PATH="$PATH:$JAVA_HOME/bin"

The /etc/profile & /etc/profile.d/*.sh files

The /etc/profile is often used for setting system-wide environment variables but it is a configuration file so it's inappropriate to edit that file. The /etc/profile.d directory should be used instead. It (and any sh files inside) get executed whenever a bash login shell is entered (e.g. when logging in from the console or over ssh), as well as by the DisplayManager when the desktop session loads. 

For example, create the /etc/profile.d/myvars.sh file and set the variables as followings:

export JAVA_HOME=/usr/local/jdk-15.0.2
export PATH="$PATH:$JAVA_HOME/bin"



No comments:

Post a Comment