AI Hints
Home›Linux Tutorial›The Environment
Linux · Lesson 85 of 120

Environment Variables

Settings for every program.

⏱ 2 min read▶ Video at 1:53:28🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

Programs often need to know a few things about you. Your username, your home folder, your language. Instead of asking every time, they read environment variables. Little named settings, that every program can see.

Environment Variables
From the video: Environment Variables
  • Programs need to know things
  • Your name, home, language
  • Environment variables

Reading variables

A variable's name is usually in capitals. To use its value, put a dollar sign in front. Echo dollar home prints Sam's home folder. Echo dollar user prints the username. And print env lists every environment variable at once. Here we show just a few.

Terminal
echo $HOME
/home/sam
echo $USER
sam
printenv | grep -E "^(HOME|USER|LANG|SHELL)="
SHELL=/bin/bash
HOME=/home/sam
LANG=C.UTF-8
USER=sam

Making your own

You can create your own variables. Name equals value, with no spaces around the equals sign. Then use it with a dollar sign. Export turns it into an environment variable, so programs you start can see it too, not just this shell.

Terminal
city=London
echo "I live in $city"
I live in London
export city
bash -c 'echo "A child program sees $city"'
A child program sees London

Spaces and quotes

The most common mistake is putting spaces around the equals sign. City space equals London means, run a command called city. And use double quotes around text with variables. Double quotes still expand dollar signs. Single quotes don't, they print the text exactly as written.

keyvalue
city=Londoncorrect
city = Londonwrong: runs 'city'
"$city"expands
'$city'prints $city literally

Summary

Environment variables are named settings. Dollar name reads one, name equals value sets one, and export shares it with other programs. Next, the most important variable of all, path.

Key takeaways
  • echo $HOME
  • name=value
  • export name
Next up: The PATH Variable — how the shell finds programs