Lab 18: Environment Variables

Objective

Understand, inspect, set, and use environment variables: PATH, HOME, USER, export, .bashrc, .profile, and how environment variables control program behaviour and pass configuration to applications.

Time: 25 minutes | Level: Foundations | Docker: docker run -it --rm ubuntu:22.04 bash


Step 1: Viewing Environment Variables

printenv | head -8

📸 Verified Output:

HOSTNAME=b77d3fb36284
PWD=/
HOME=/root
SHLVL=0
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
_=/usr/bin/printenv
echo "HOME:  $HOME"
echo "PATH:  $PATH"

📸 Verified Output:

HOME:  /root
PATH:  /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

💡 Variables are accessed by prefixing with $. $HOME expands to /root. Curly braces ${HOME} are equivalent and required when concatenating: ${HOME}_backup.


Step 2: The PATH Variable

PATH is a colon-separated list of directories searched when you type a command:

📸 Verified Output:

📸 Verified Output:

💡 The shell searches PATH left-to-right. Putting a directory first gives it priority. Security note: attackers who control a directory earlier in PATH can plant fake ls, cat, etc. — always verify PATH is trusted on compromised systems.


Step 3: Setting and Exporting Variables

📸 Verified Output:

📸 Verified Output:

💡 Without export, child processes (scripts you call) cannot see the variable. With export, it's in the environment — all child processes inherit it automatically.


Step 4: Variable Expansion and Defaults

📸 Verified Output:

📸 Verified Output:

📸 Verified Output:


Step 5: Unsetting Variables

📸 Verified Output:


Step 6: Persistent Variables — .bashrc and .profile

📸 Verified Output:

📸 Verified Output:

💡 .bashrc loads for every new interactive shell. .profile loads for login shells. Changes take effect in new sessions — or run source ~/.bashrc to apply immediately in the current shell.


Step 7: Per-Command Environment

📸 Verified Output:


Step 8: Capstone — 12-Factor App Config Validator

📸 Verified Output:


Summary

Command / Syntax
Purpose

echo $VAR

Print variable

export VAR=val

Set + export to child processes

unset VAR

Delete variable

printenv

Print all environment

env

Same as printenv

${VAR:-default}

Use default if unset

$(command)

Command substitution

VAR=x cmd

Set variable for one command only

source ~/.bashrc

Reload config in current shell

which cmd

Find command location in PATH

Last updated