On Ubuntu, there are two system-wide environment variables, both files need admin or sudo to modify it.

/etc/environment – It is not a script file, purely assignment expressions, one per line.

/etc/environment

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
JAVA_HOME=/usr/lib/jvm/adoptopenjdk-11-hotspot-amd64
LD_LIBRARY_PATH=/usr/local/lib:/usr/lib/postgresql/8.3/lib

/etc/profile.d/*.sh – Files with .sh extension in the /etc/profile.d/ folder.

/etc/profile.d/myenv.sh

export JAVA_HOME=JAVA_HOME=/usr/lib/jvm/adoptopenjdk-11-hotspot-amd64
export LD_LIBRARY_PATH=/usr/local/lib:/usr/lib/postgresql/8.3/lib
export PATH=$PATH:$JAVA_HOME/bin

Further Reading: Ubuntu – EnvironmentVariables

1. /etc/environment

1.1 Add a new environment variable MY_HOME=/home/favtuts in the /etc/environment file and source it to reflect the changes.

$ sudo vim /etc/environment

1.2 Modify, save and exit.

/etc/environment

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
JAVA_HOME=/usr/lib/jvm/adoptopenjdk-11-hotspot-amd64
LD_LIBRARY_PATH=/usr/local/lib:/usr/lib/postgresql/8.3/lib
MY_HOME=/home/favtuts

1.3 Test.

$ source /etc/environment

$ echo $MY_HOME
/home/favtuts

Note

The new changes in /etc/environment will disappear if we close the current session or reopen a new terminal because a new shell does not trigger the /etc/environment. Try to restart the Ubuntu or login again; the new changes in /etc/environment will apply automatically.

2. /etc/profile.d/new-env.sh

2.1 Add a new environment variable MY_HOME=/home/favtuts in the /etc/profile.d/new-env.sh file and source it to reflect the changes.

$ sudo vim /etc/environment

2.2 Create, save and exit.

/etc/profile.d/new-env.sh

export MY_HOME=/home/favtuts

2.3 Test.

$ source /etc/profile

$ echo $MY_HOME
/home/favtuts

2.4 Why source /etc/profile? Read the source code, it will execute all files with .sh extension.

/etc/profile

# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

if [ "${PS1-}" ]; then
  if [ "${BASH-}" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    fi
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

References

Leave a Reply

Your email address will not be published. Required fields are marked *