What is an environment variable?
An environment variable is a named setting that programs can read. It is like a sticky note with a name and a value. For example, HOME holds the path to your home folder. Programs read these notes to know how to behave.
You need SSH access to follow along. SSH is a safe way to type commands on a remote server.
Read variables
- Log in to your server over SSH.
- List all variables.
printenv
This prints every variable and its value.
- Show just one.
echo $HOME
The dollar sign tells the shell to give you the value.
- Look at the list of folders the system searches for programs.
echo $PATH
Set a variable for the current session
This lasts until you log out.
- Create the variable. No spaces around the equal sign.
MY_NAME="Hostvento"
- Make it visible to programs you start. This is called exporting.
export MY_NAME
- Check it.
echo $MY_NAME
To remove it, type unset MY_NAME.
Save a variable for your user
- Open the file
~/.bashrcin a text editor such as nano.
nano ~/.bashrc
- Go to the end and add a line.
export MY_NAME="Hostvento"
- Save the file. In nano, press Ctrl+O, Enter, then Ctrl+X.
- Load the change.
source ~/.bashrc
Save a variable for all users (root needed)
This step needs root access and affects everyone. Take a backup of the file first.
- Copy the file for safety.
sudo cp /etc/environment /etc/environment.bak
- Open
/etc/environmentand add a line likeMY_NAME="Hostvento". Do not use the word export here. - Log out and back in.
Another way is to put an export line in a file inside /etc/profile.d/, ending in .sh.
Add to PATH
export PATH=$PATH:/opt/mytool/bin
This adds a folder to the search list without removing the old ones. Never write PATH=/opt/mytool/bin alone, or the system will stop finding normal commands.
Quick recap
- Environment variables are named settings that programs read.
- Read them with
printenvandecho $NAME. - Set them with
export NAME=value. - Save them in
~/.bashrcor/etc/environment.