5.1 Shell Environment, Environment Variables & Aliases (103.1)
Key Takeaways
- Shell (local) variables exist only within the current shell process, whereas environment (global) variables are exported to child processes via export or declare -x.
- System environment variables (PATH, HOME, USER, SHELL, PWD, HISTSIZE, PS1, LC_ALL) control execution paths, localization, and prompt behavior.
- Login shells execute /etc/profile followed by the first readable file among ~/.bash_profile, ~/.bash_login, and ~/.profile; non-login interactive shells read /etc/bash.bashrc and ~/.bashrc.
- Aliases provide command shortcuts via alias name='command'; they can be inspected with alias, removed with unalias, or bypassed using a leading backslash (\command).
- Non-interactive script execution does not read standard profile or rc files by default, relying instead on the environment variable BASH_ENV.
5.1 Shell Environment, Environment Variables & Aliases (103.1)
Quick Summary: The Linux shell provides an interactive execution environment governed by shell variables, environment variables, initialization startup scripts, and command aliases. Understanding variable scope, exporting mechanics (
export,declare -x), diagnostic inspection tools (env,printenv,set,unset), shell initialization cascades (/etc/profile,~/.bash_profile,~/.bashrc), and alias management is critical for Topic 103.1 on the LPIC-1 exam.
1. Shell Variables vs. Environment Variables
In the GNU Bash shell, variables store textual strings and configuration parameters. Linux distinguishes fundamentally between two classes of variables based on inheritance and process scope:
Variable Scope Hierarchy:
┌─────────────────────────────────────────────────────────────────────────┐
│ Parent Shell (PID 1000) │
│ • Shell Variable: LOCAL_VAR="data" (Visible in PID 1000 only) │
│ • Environment Variable: export ENV_VAR="data" (Exported to Environment) │
└────────────────────────────────────┬────────────────────────────────────┘
│ Forks child process
▼
┌─────────────────────────────────────────────────────────────────────────┐
│ Child Process / Subshell (PID 1001) │
│ • LOCAL_VAR is NOT inherited (Empty / Unset) │
│ • ENV_VAR is inherited by copy (Value = "data") │
│ • Changes made in PID 1001 NEVER propagate back to parent PID 1000! │
└─────────────────────────────────────────────────────────────────────────┘
Core Differences
- Shell Variables (Local Variables):
- Defined directly using
NAME=value(no spaces around the=assignment operator). - Accessible only within the current running shell process.
- Child processes, executed binary utilities, and spawned subshells do not inherit local shell variables.
- Defined directly using
- Environment Variables (Global Variables):
- Exported to the process environment table using
exportordeclare -x. - Automatically passed by copy to every child process forked by the shell.
- Child isolation rule: If a child process alters an environment variable, that alteration affects only the child and its descendants; it cannot modify the environment table of the parent shell.
- Exported to the process environment table using
Variable Assignment, Exporting & Removal Commands
# Assigning a local shell variable (not passed to child processes)
MY_SERVER="web01.example.internal"
# Exporting an existing variable into the environment table
export MY_SERVER
# Defining and exporting in a single operation
export DATABASE_HOST="db.example.internal"
declare -x DATABASE_PORT="5432"
# Verifying inheritance in a subshell
bash -c 'echo "Server: $MY_SERVER, DB: $DATABASE_HOST"'
# Output: Server: web01.example.internal, DB: db.example.internal
# Removing a variable from memory and the environment
unset MY_SERVER
unset DATABASE_HOST
Variable Inspection Utilities Compared
| Command | Type | Scope Displayed | Displays Functions? | Accepts Arguments? |
|---|---|---|---|---|
env | External (/usr/bin/env) | Environment (exported) variables only | No | Can run commands in modified environment: env VAR=val cmd |
printenv | External (/usr/bin/printenv) | Environment (exported) variables only | No | Can query a single variable directly: printenv PATH |
set | Shell Built-in | All shell variables, environment variables, and shell functions | Yes | Also used to toggle shell runtime options (set -o nounset) |
declare -p | Shell Built-in | All variables with attributes (-x exported, -r readonly, -a array) | No | declare -p VAR prints exact attribute and value definition |
💡 LPIC-1 Exam Fill-in-the-Blank Alert: When an exam prompt asks for the shell built-in command used to remove environment or shell variables from memory, the exact command is
unset. When asked for the utility to display both shell variables and shell functions, enterset.
2. Essential System Environment Variables
The Linux operating system and user applications rely on standardized environment variables to control operational behavior, system paths, history storage, and localization.
| Environment Variable | Description & Standard Format | Practical Example / Inspection |
|---|---|---|
PATH | Colon-separated list of directories searched sequentially for executable binaries | PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" |
HOME | Absolute path to the current user's home directory | /home/student or /root |
USER / LOGNAME | The username of the currently logged-in user | student |
SHELL | Absolute path to the user's default login shell binary | /bin/bash |
PWD | Current working directory (updated automatically on cd) | /var/log/audit |
OLDPWD | Previous working directory (accessed when running cd -) | /etc/systemd |
HISTSIZE | Maximum number of command lines held in in-memory history buffer | 1000 |
HISTFILESIZE | Maximum number of command lines stored on disk in the history file | 2000 |
HISTFILE | Absolute path to the file storing command history across sessions | ~/.bash_history (or /home/user/.bash_history) |
PS1 | Primary interactive shell prompt string | [\\u@\\h \\W]\$ |
PS2 | Secondary prompt displayed when a command spans multiple lines | > |
TERM | Terminal emulation identifier controlling escape sequences | xterm-256color, vt100, linux |
EDITOR / VISUAL | Default text editor invoked by tools like crontab -e and visudo | /usr/bin/nano, vi, vim |
PAGER | Default terminal pager used for displaying long text streams (e.g. man) | less, more |
LANG | System-wide default locale (character set, language, collation) | en_US.UTF-8, C.UTF-8 |
LC_ALL | Universal locale override that takes precedence over all other LC_* variables | C (standard POSIX ASCII sorting/messages) |
Manipulating and Appending to $PATH
When a user enters a command without specifying an absolute or relative path (e.g., tar instead of /usr/bin/tar), the shell searches each directory listed in $PATH from left to right, executing the first matching binary found. If the command is not located in any listed directory, the shell returns exit code 127 (command not found).
# Appending a custom software directory to the end of PATH
export PATH="$PATH:/opt/custom/bin"
# Prepending a directory so its binaries take precedence over system defaults
export PATH="/usr/local/special/bin:$PATH"
⚠️ LPIC-1 Trap: Never include the current directory
.or an empty path::at the beginning of$PATHon production servers. If an attacker places a malicious binary namedlsin/tmpand an administrator runslsinside/tmp, the malicious binary would execute instead of/usr/bin/ls.
Primary Prompt (PS1) Escape Sequences
The primary shell prompt variable PS1 supports special backslash-escaped characters:
\\u: Current username\\h: Hostname up to the first dot (.)\\H: Full Fully Qualified Domain Name (FQDN) hostname\\w: Full current working directory path (with$HOMErepresented as~)\\W: Basename of the current working directory\\d: Date in "Weekday Month Date" format\\t: Current time in 24-hour HH:MM:SS format\\$: Displays#if the effective UID is 0 (root), or$for standard unprivileged users
# Setting an informative, secure administrator prompt:
export PS1="[\\u@\\h \\w]\$ "
3. Shell Initialization Startup Files & Loading Sequence
Bash executes different configuration scripts depending on how it is invoked. The exam tests the exact sequence and priority of these files.
A. Login Shells (Interactive Login)
A login shell is initiated when a user authenticates via local text console (TTY), connects via SSH, runs su - username (or su -l), or explicitly launches bash --login.
- System-wide configuration:
/etc/profile: Executed first for all users. It sets default$PATH,$USER,umask, and sources modular configuration scripts located in/etc/profile.d/*.sh.
- User-specific configuration (Strict First-Found Precedence):
- Bash inspects the user's home directory and executes the first readable file found among the following three files, ignoring the remaining two:
~/.bash_profile(highest precedence)~/.bash_login(second precedence)~/.profile(fallback standard POSIX file)
- Bash inspects the user's home directory and executes the first readable file found among the following three files, ignoring the remaining two:
- Logout / Termination:
- When a login shell exits, it executes
~/.bash_logoutfollowed by/etc/bash.bash_logout(if present) to clear temporary files or terminal screens.
- When a login shell exits, it executes
B. Interactive Non-Login Shells
An interactive non-login shell is started when opening a terminal window inside a desktop GUI (GNOME Terminal, Konsole), typing bash inside an existing session, or switching users via su username (without the - or -l switch).
/etc/bash.bashrc(Debian/Ubuntu) or/etc/bashrc(RHEL/CentOS/Fedora): System-wide functions and aliases.~/.bashrc: User-specific environment customizations, aliases, and functions. In standard distributions,~/.bash_profileexplicitly contains lines to source~/.bashrc.
C. Non-Interactive Shells (Script Execution)
When a shell script executes (./backup.sh or bash script.sh), the non-interactive shell does not load /etc/profile, ~/.bash_profile, or ~/.bashrc. Instead, it checks if the BASH_ENV environment variable is set; if so, it expands its value and sources the referenced file before running the script.
4. Shell Aliases: Creation, Inspection, and Bypassing
Aliases allow users to define custom shorthand abbreviations for long commands, default flags, or complex pipeline invocations.
Managing Aliases
# Creating command aliases
alias ll='ls -la --color=auto'
alias rm='rm -i'
alias grep='grep --color=auto'
# Listing all currently active aliases
alias
# Viewing the specific definition of a single alias
alias ll
# Output: alias ll='ls -la --color=auto'
# Removing a single alias
unalias ll
# Removing ALL defined aliases in the current session
unalias -a
Bypassing Defined Aliases
When an alias is assigned to a standard command name (such as alias rm='rm -i'), an administrator may occasionally need to invoke the original binary without alias modification. Linux provides four mechanisms to bypass aliases:
- Leading Backslash (
\command):m file.txtescapes alias expansion. - The
commandBuilt-in:command rm file.txtruns the external or built-in command, ignoring aliases. - The
builtinBuilt-in:builtin echo "test"forces execution of the shell built-in. - Absolute or Relative Path:
/bin/rm file.txtor./script.shbypasses alias resolution completely because aliases only match unquoted first words without path slashes.
💡 LPIC-1 Exam Fill-in-the-Blank Alert: To make an alias persistent across all future interactive shell sessions for a specific user, the
aliasdefinition must be written into the user's~/.bashrcfile.
A Linux administrator needs to create a variable named APP_ENV with the value 'staging' and ensure it is automatically inherited by all child processes and scripts launched from the current shell. Which command accomplishes this?
When a user logs into a Linux system via SSH, which user-specific startup file in the user's home directory is evaluated FIRST by the Bash login shell if all files are present?
An alias is defined as alias cp='cp -i'. Which syntax allows a system administrator to execute the standard cp command directly while bypassing the alias confirmation prompt?