Intermediate · 8 min · practise every command in the built-in terminal

Environment Variables

Variables store data that programs and the shell can read.

Setting variables

MYNAME="IVski"              # Shell variable (local)
export MYNAME="IVski"        # Environment variable (inherited by subprocesses)

Reading variables

echo $MYNAME
echo ${MYNAME}               # Safer: braces avoid ambiguity
echo "Hello, ${MYNAME}!"

Viewing variables

env                          # All environment variables
printenv                     # Same
printenv HOME                # Specific variable
set                          # All shell variables (more than env)

Important built-in variables

VariableMeaning
$HOMEYour home directory
$USERYour username
$SHELLYour current shell
$PATHWhere commands are looked up
$PWDCurrent directory
$TERMTerminal type
$EDITORDefault text editor
$?Exit code of last command
$$PID of current shell
$!PID of last background process

Exit codes

ls /exists         # Returns 0 (success)
echo $?            # Prints 0
ls /notexist       # Returns 2 (error)
echo $?            # Prints 2

0 = success, anything else = error.

Practice tasks

  1. Create a variable MY_NAME with your name, then print it
  2. Print all environment variables
  3. Export a CITY variable and confirm it shows up as an environment variable
  4. Check the exit code of your last command

Commands in this lesson

Shell & Environment