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.
Last updated: August 2026

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

  1. 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.
  2. Environment Variables (Global Variables):
    • Exported to the process environment table using export or declare -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.

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

CommandTypeScope DisplayedDisplays Functions?Accepts Arguments?
envExternal (/usr/bin/env)Environment (exported) variables onlyNoCan run commands in modified environment: env VAR=val cmd
printenvExternal (/usr/bin/printenv)Environment (exported) variables onlyNoCan query a single variable directly: printenv PATH
setShell Built-inAll shell variables, environment variables, and shell functionsYesAlso used to toggle shell runtime options (set -o nounset)
declare -pShell Built-inAll variables with attributes (-x exported, -r readonly, -a array)Nodeclare -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, enter set.


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 VariableDescription & Standard FormatPractical Example / Inspection
PATHColon-separated list of directories searched sequentially for executable binariesPATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
HOMEAbsolute path to the current user's home directory/home/student or /root
USER / LOGNAMEThe username of the currently logged-in userstudent
SHELLAbsolute path to the user's default login shell binary/bin/bash
PWDCurrent working directory (updated automatically on cd)/var/log/audit
OLDPWDPrevious working directory (accessed when running cd -)/etc/systemd
HISTSIZEMaximum number of command lines held in in-memory history buffer1000
HISTFILESIZEMaximum number of command lines stored on disk in the history file2000
HISTFILEAbsolute path to the file storing command history across sessions~/.bash_history (or /home/user/.bash_history)
PS1Primary interactive shell prompt string[\\u@\\h \\W]\$
PS2Secondary prompt displayed when a command spans multiple lines>
TERMTerminal emulation identifier controlling escape sequencesxterm-256color, vt100, linux
EDITOR / VISUALDefault text editor invoked by tools like crontab -e and visudo/usr/bin/nano, vi, vim
PAGERDefault terminal pager used for displaying long text streams (e.g. man)less, more
LANGSystem-wide default locale (character set, language, collation)en_US.UTF-8, C.UTF-8
LC_ALLUniversal locale override that takes precedence over all other LC_* variablesC (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 $PATH on production servers. If an attacker places a malicious binary named ls in /tmp and an administrator runs ls inside /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 $HOME represented 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]\$ "
Loading diagram...
Bash Startup and Configuration File Execution Flow

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.

  1. 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.
  2. 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:
      1. ~/.bash_profile (highest precedence)
      2. ~/.bash_login (second precedence)
      3. ~/.profile (fallback standard POSIX file)
  3. Logout / Termination:
    • When a login shell exits, it executes ~/.bash_logout followed by /etc/bash.bash_logout (if present) to clear temporary files or terminal screens.

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).

  1. /etc/bash.bashrc (Debian/Ubuntu) or /etc/bashrc (RHEL/CentOS/Fedora): System-wide functions and aliases.
  2. ~/.bashrc: User-specific environment customizations, aliases, and functions. In standard distributions, ~/.bash_profile explicitly 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:

  1. Leading Backslash (\command): m file.txt escapes alias expansion.
  2. The command Built-in: command rm file.txt runs the external or built-in command, ignoring aliases.
  3. The builtin Built-in: builtin echo "test" forces execution of the shell built-in.
  4. Absolute or Relative Path: /bin/rm file.txt or ./script.sh bypasses 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 alias definition must be written into the user's ~/.bashrc file.

Test Your Knowledge

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?

A
B
C
D
Test Your Knowledge

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?

A
B
C
D
Test Your Knowledge

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?

A
B
C
D