student@ubuntu:~$
shell 2/5 25 XP

Environment Variables

0%

Quick Reference

Command What It Does
echo $VAR Print a variable’s value
env List all environment variables
export VAR="val" Set variable, visible to child processes
VAR="val" Set variable, current shell only
unset VAR Remove a variable
which cmd Show where a command lives in PATH
alias ll='ls -la' Create a command shortcut
unalias ll Remove an alias
source ~/.bashrc Reload shell config without restarting

Key variables:

Variable Contains Example Value
HOME Home directory /home/student
USER Username student
PATH Command search dirs (colon-separated) /usr/local/bin:/usr/bin:/bin
SHELL Default shell /bin/bash
PWD Current working directory /home/student/cscd240
EDITOR Preferred text editor vim

Quoting rules:

Syntax Variable expansion? Example
"double quotes" Yes "Hello $USER"Hello student
'single quotes' No (literal) 'Hello $USER'Hello $USER
No quotes Yes (plus word splitting) Avoid for strings with spaces

How It Works

Viewing and Setting Variables

Terminal
student@ubuntu:~$ echo $HOME
/home/student

student@ubuntu:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

student@ubuntu:~$ which gcc
/usr/bin/gcc

PATH and ./program

Terminal
student@ubuntu:~/cscd240$ gcc hello.c -o hello

student@ubuntu:~/cscd240$ hello
hello: command not found

student@ubuntu:~/cscd240$ ./hello
Hello, World!

The current directory (.) is not in PATH by default. This is a security feature – prevents running a malicious ls that happens to be in your download folder.

Quoting and Export

Terminal
student@ubuntu:~$ COURSE="CSCD 240"

# Double quotes: variable expanded
student@ubuntu:~$ echo "Welcome to $COURSE"
Welcome to CSCD 240

# Single quotes: literal text
student@ubuntu:~$ echo 'Welcome to $COURSE'
Welcome to $COURSE

# Export for child processes
student@ubuntu:~$ export COURSE="CSCD 240"

Making It Permanent: .bashrc

# Add to ~/.bashrc
export EDITOR=vim
export PATH="$PATH:$HOME/bin"
alias ll='ls -la'
alias compile='gcc -Wall -o'

Then run source ~/.bashrc or open a new terminal.

Common Pitfalls

  • No spaces around =. X=5 works. X = 5 runs a command called X. This bites everyone at least once.
  • export vs plain assignment. Without export, child processes can’t see your variable. If a script can’t find your variable, you probably forgot to export it.
  • .bashrc edits don’t auto-apply. You must source ~/.bashrc or open a new terminal.
  • Overwriting PATH. PATH=~/bin replaces your entire PATH. Use PATH=$PATH:~/bin to append.
  • echo HOME vs echo $HOME. Without the $, you get the literal string “HOME”, not the variable’s value.

Unlocks

Complete this skill to see what it unlocks.