Ubuntu – Setting system-wide environment variable using /etc/environment

bashcommand lineenvironment-variablesr

I want to add to my PATH so that my computer (Ubuntu) knows where to interpret the "R" command (for launching R). I need this so a Terminal or RStudio can find where I installed R.

I did all of the following, none of which permanently associates the command R with the directory of my R installation in ~/R/bin.

  1. export PATH=$PATH:$HOME/R/bin <- This works within the Terminal session it was enacted in, but if I open up a second terminal, PATH goes back to what it was before I added $HOME/R/bin to it

The same "local Terminal only" behavior occurred when I added this line to two different files, based on recommendations on various websites:

  1. sudo vim ~/.profile

    export PATH=$PATH:$HOME/R/bin
    
  2. sudo vim /etc/environment

    export PATH=$PATH:$HOME/R/bin
    

Why won't R be recognized in new Terminal sessions?

Best Answer

The /etc/environment file is not a script file: AFAIK you can't use export there and it doesn't support variable expansion of the type $HOME, just simplevariable=value pairs. So to use that file, you'd need to simply append your path to the existing definition, like

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/username/R/bin"

However, setting the system-wide PATH to include a user's home directory in this way is a questionable practice IMHO: the normal way would be to use one of the user's own shell startup files: ~/.profile is usually the recommended one for environment variables, however it has the disadvantage of only being invoked by login shells, so in order to get it to take effect you will need to log out and back in - or at least, start a new login shell e.g. using

    su - username

or

    su -l username

Note that sudo should not be used to edit these personal files, as it will likely leave them owned by root, which can cause further problems down the road. If you have already used sudo vim you may need to use sudo chown to restore their correct ownership e.g.

sudo chown username:username ~/.profile

Then you can add the desired path component using your preferred editor e.g.

vim ~/.profile

You could even consider copying the existing paradigm for ~/bin in that file i.e. add it as

# set PATH so it includes user's private R bin if it exists
if [ -d "$HOME/R/bin" ] ; then
    PATH="$HOME/R/bin:$PATH"
fi
Related Question