Bash — Environment Variables
Common environment variables
echo $HOME # Home directory
echo $USER # Current user
echo $SHELL # Current shell
echo $PATH # Executable path
echo $PWD # Current directory
echo $LANG # Language
echo $EDITOR # Default editor
Setting variables
#!/bin/bash
# Local variable (only in current shell)
my_var="hello"
# Export to environment
export MY_VAR="hello"
# Set and export
export NAME="Alice"
PATH manipulation
#!/bin/bash
# Add to PATH
export PATH="$PATH:/new/path"
# Prepend to PATH
export PATH="/new/path:$PATH"
# Remove from PATH
export PATH=$(echo "$PATH" | sed 's|/old/path:||')
Shell configuration files
| File | Purpose |
|---|---|
~/.bashrc | Interactive shell config |
~/.bash_profile | Login shell config |
~/.profile | Login shell config (POSIX) |
/etc/bash.bashrc | System-wide config |
/etc/profile | System-wide login config |
Aliases
# Create alias
alias ll='ls -la'
alias gs='git status'
alias gp='git push'
# Remove alias
unalias ll
# Make permanent (add to ~/.bashrc)
echo "alias ll='ls -la'" >> ~/.bashrc
Mini Practice
Write Bash code that:
- Prints common environment variables
- Sets and exports a custom variable
- Adds a directory to PATH
- Creates an alias
Up Next
In the next lesson, you'll learn about Regular Expressions — pattern matching in Bash.
Related Topics
Frequently Asked Questions about Environment Variables
What is Environment Variables in Bash?
Environment Variables is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Environment Variables?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Environment Variables.
Why is Environment Variables important in Bash?
Environment Variables is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.