Chapter 4: The Environment
Your shell session is not just a blank slate; it is a dynamic environment populated with variables, aliases, and settings that define how you interact with the system. Mastering the environment is the first step toward building a personalized, efficient workflow.
I. Global vs. Local Variables
The shell distinguishes between variables that are local to the current session and those that are "exported" to child processes.
| Type | Scope | Definition | Access |
|---|---|---|---|
| Shell Variable | Local | MY_VAR="hello" | Only current shell |
| Environment Variable | Global | export MY_VAR="hello" | Current shell + all sub-processes |
Common Environment Variables:
$USER: The current logged-in username.$HOME: Path to your home directory.$SHELL: The path to the shell binary you are using.$EDITOR: Your preferred text editor (e.g.,vim,nano).$LANG: The system's language and character encoding (e.g.,en_US.UTF-8).
II. The PATH: A System-Wide Map
The most critical environment variable is $PATH. It is a colon-separated list of directories where the shell looks for executable files.
III. Shell Configuration (Dotfiles)
To make settings permanent, you add them to configuration files in your home directory.
- Login Shells (e.g., SSH, initial login):
- Reads
~/.bash_profileor~/.zprofile.
- Reads
- Non-Login Shells (e.g., opening a new terminal tab):
- Reads
~/.bashrcor~/.zshrc.
- Reads
Pro Tip:
Always put your export commands and alias definitions in ~/.bashrc (for Bash) or ~/.zshrc (for Zsh) to ensure they are available everywhere.
IV. Customizing the Prompt (PS1)
The text you see before your cursor is controlled by the $PS1 variable. You can use special escape characters to show the time, user, or current directory.
| Escape | Meaning |
|---|---|
\u | Current username |
\h | Hostname (short) |
\w | Current working directory (full path) |
\W | Current working directory (basename) |
\t | Current time (24h) |
Example:
export PS1="[\u@\h \W]\$ "
# Result: [jane@laptop docs]$
V. Aliases: Productivity Shortcuts
Aliases allow you to create short names for long, complex commands.
# Add these to your .zshrc or .bashrc
alias ls='ls --color=auto'
alias ll='ls -lah'
alias gs='git status'
alias gcm='git commit -m'
In the next chapter, we'll stop typing manual commands and learn how to package them into Shell Scripts.