Understanding Environment Variables
Environment variables are named values that affect how processes run. They store configuration, paths, and settings that programs need.
What Are Environment Variables?
Environment variables are:
- Key-value pairs stored in the shell
- Inherited by child processes
- Used to configure programs
- Available system-wide or per-session
Viewing Variables
See All Variables
env
printenv
See Specific Variable
echo $HOME
echo $USER
echo $PATH
printenv HOME
Common Environment Variables
| Variable | Description |
|---|---|
HOME | User's home directory |
USER | Current username |
PATH | Directories to search for commands |
PWD | Current working directory |
SHELL | Current shell program |
TERM | Terminal type |
LANG | Language setting |
EDITOR | Default text editor |
Exercise: View an Environment Variable
Display the value of the HOME variable:
Variable Syntax
$VARIABLE # Access value
${VARIABLE} # Access value (safer in strings)
${VARIABLE:-default} # Default if unset
${VARIABLE:=default} # Set default if unset
Examples:
echo "Home is $HOME"
echo "User: ${USER}"
echo "${UNDEFINED:-not set}"
Types of Variables
Environment Variables
Available to child processes:
export MY_VAR="value"
Shell Variables
Only in current shell:
my_var="value"
Where Variables Are Set
| File | When Loaded |
|---|---|
/etc/environment | System-wide, all users |
/etc/profile | Login shells, all users |
~/.bashrc | Interactive non-login shells |
~/.profile | Login shells |
~/.bash_profile | Bash login shells |
Checking if Variable Exists
# Check if set
if [ -z "$VARIABLE" ]; then
echo "Not set"
fi
# Check if not empty
if [ -n "$VARIABLE" ]; then
echo "Has value"
fi
Using Variables in Commands
cd $HOME
ls $HOME/documents
cat ${HOME}/.bashrc
Exercise: List All Variables
Use env to see all environment variables:
Key Takeaways
- Environment variables store configuration values
- Access with
$VARIABLEor${VARIABLE} - Common ones:
HOME,PATH,USER - Use
envorprintenvto list all - Shell vs environment variables have different scope
التالي · الدرس 27 من 40
Setting and Exporting Variables
قراءة 1 دقيقة
أنهيت 26 من 40 درسًا

اسأل Byte عن هذا الدرس
محادثة خاصة حول هذا الدرس. قرأ Byte الدرس كاملًا، ويجيب خلال ثوانٍ، ويُظهر القسم الذي تأتي منه كل إجابة. يمكنك السؤال بأي لغة.
الأسئلة والأجوبة
أسئلة عامة حول هذا الدرس. يجيب AI Tutor فورًا بلغتك، ويراجع فريق FreeAcademy الإجابات، ويمكن لكل المتعلمين قراءتها.

