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
| Variable | Meaning |
|---|---|
$HOME | Your home directory |
$USER | Your username |
$SHELL | Your current shell |
$PATH | Where commands are looked up |
$PWD | Current directory |
$TERM | Terminal type |
$EDITOR | Default 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.