Wednesday, May 14, 2014

Setting environment variables in Linux

In this post I take a closer look at setting environment variables in Linux. For this purpose, it is common to use the /etc/profile for the system, or ~/profile for the user settings.

Setting environment variables from ordinary bash script is rarely used and that is why this behavior may be for someone surprising.

Print your environment variables
$ env

Environment variables can be set for:
  • System
  • User
  • Current bash process and sub-processes

System

Interactive login shell first reads and executes commands from the file /etc/profile, if that file exists.

Some Linux systems now use a directory /etc/profile.d/; any .sh files in there will be sourced by /etc/profile.

User

After reading /etc/profile, it looks for ~/.bash_profile, ~/.bash_login, and  ~/.profile,  in  that order,  and  reads  and  executes  commands  from the first one that exists and is readable.

Process and subprocesses

$ export DB_URL=mongodb://localhost:27017/testaBD

It affect current bash process and subprocesses.

When you export variables in a bash script:

  1. It opens a new shell.
  2. It executes commands.
  3. It copies the output back to your current shell.
  4. It closes the new shell.

Any changes to environment will take effect only in the new shell and will be lost once the new shell is closed.

It's important to note that exporting a variable doesn't make it available to parent process. That is, specifying and exporting a variable in a spawned process doesn't make it available in the process that launched it.

Source a bash script

$ source script.sh

Sourcing the script does not create a new shell. All commands are run in the current shell and changes to the environment take effect in the current shell. When you source the script you are typing the commands in your current shell. Any changes to the environment will take effect and stay in your current shell.