Linux env. variables

Photo by Tanner Boriack on Unsplash

Photo by Tanner Boriack on Unsplash

Environment variables are shell variables that can be globally accessed from any program or shell script. In this article, I will show how they are configured on an Ubuntu 22 host, and how to access them using a BASH shell, and a few scripting languages.

User env. variables

To add an environment variable to your user, you simply add the declaration to your .bashrc file in your home directory. This is a shell script that runs every time a new BASH shell is created with your user.

vim ~/.bashrc
~/.bashrc
...

export HAXOR_VARIABLE="Env. variables are great!"

System env. variable

Sometimes it's nice to add system environment variables to the host. The difference between user and system environment variables is that user environment variables are only available for the user it is added to, and system environment variables are available to all users, even service users on the host.

To add a system environment variable you add it to the environment file.

sudo vim /etc/environment
/etc/environment
...

HAXOR_VARIABLE="Env. variables are great!"

BASH access

To access the environment variable through a BASH shell you prefix the variable name with a "$". A simple example is to use the echo command to print the value to the shell.

echo $HAXOR_VARIABLE
Env. variables are great!

Python access

Environment variables are easily accessed from python scripts as well. To access them you will have to import the "getenv" method from the os library. Once imported the getenv method can be used to access the environment variable by passing the environment variable name, and a default value that can be used if the environment variable was not found. In the example below I passed an empty string as a default.

env.py
#!/usr/bin/env python3
from os import getenv

ENV_VAR = getenv("HAXOR_VARIABLE","")
print(ENV_VAR)
python3 env.py
Env. variables are great!

PHP access

With PHP it's very easy to access environment variables, you just use the built-in getenv() function to access the variable by its name.

env.php
<?php
$ENV_VAR = getenv('HAXOR_VARIABLE');
var_dump($ENV_VAR)
?>
php env.php
string(24) "Env. variables are great!"

node.js access

With node.js it's also very simple to access the environment variables. Here you access the variable through the process object.

env.js
const ENV_VAR = process.env.HAXOR_VARIABLE;
console.log(ENV_VAR);
node env.js
Env. variables are great!