Environment Variables in Unix

Each process in Unix has its own set of environment variables. They’re called environment variables because the default set of such variables consists mostly of session-wide variables used for configuration purposes.

From the point of a Unix shell though, environment variables can be accessed the same way as any other variable.

Common environment variables in Unix

Most well known environment variables are the following:

  • USER – username of a Unix user
  • HOME – full path to a user’s home directory
  • TERM – terminal or terminal emulator used by a current user
  • PATH – list of directories searched for executable files when you type a command in Unix shell
  • PWD – current directory

Example of using environment variables

Using Unix username to control the flow of a script

Sometimes it’s quite useful to double-check the username of whoever called your script – maybe you’ll want to provide different functionality for different users. A common use of such scenario is many commands which are not meant to be run by anyone except superuser (root). If you try running them as a normal user, you’ll be told right away that you have to be root in order to use them.

In Unix scripts, the opposite functionality is more useful: making sure you don’t run a script as root. Here’s one way of doing it:

echo "- Verifying the current user..."
if [ "$USER" = "root" ]; then
        echo "You are ROOT, please run as a normal user";
        echo "User $USER, script is ready to continue"
        echo "Work in progress..."

And that’s how it would work:

ubuntu$ /tmp/script.sh
- Verifying the current user...
User greys, script is ready to continue
Work in progress...

If I use sudo in Ubuntu to run the script as root, I’ll get a warning and the script will end:

$ sudo /tmp/script.sh
- Verifying the current user...
You are ROOT, please run as a normal user

Getting full list of environment variables

In case you feel like exploring, you can use the env command to get a full list of currently set environment variables (the output in this example is abridged):

ubuntu$ env

That’s all I wanted to share with you today. Let me know how exactly you’d like me to further expand and cover this topic – more posts will definitely follow!
h3>Recommended books:

See also: