Fundamentals 17 min read

Master Linux Environment Variables and Bash: A Complete Guide

This article provides a comprehensive overview of Linux environment variables, common and special variables, Bash shell fundamentals, login script execution order, variable manipulation techniques, and essential built‑in commands, helping readers understand and effectively use shell scripting on Unix‑like systems.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Linux Environment Variables and Bash: A Complete Guide

1. Introduction to Environment Variables

Linux is a multi‑user operating system. After a user logs in, a dedicated runtime environment is created, which by default is defined by a set of environment variables. These variables are global and can be used by all programs run by the current user. Users can customize their environment by modifying system environment variables.
Common environment variables:
PATH: determines directories where the shell looks for commands.
ROOTPATH: similar to PATH but only for the super‑user.
HOME: current user's home directory.
USER: shows the current user.
LOGNAME: shows the login name of the current user.
UID: numeric user identifier.
SHELL: the shell program in use.
TERM: terminal type.
PWD: absolute path of the current working directory (changes with cd).
MAIL: directory where the user's mail is stored.
HISTSIZE: number of command history entries saved.
HOSTNAME: system's host name.
PS1: primary prompt ("#" for root, "$" for normal users).
PS2: secondary prompt, default ">"; can be changed, e.g., PS1="Hello,My NewPrompt :)".
IFS: input field separator (space, tab, newline by default).
Important locale‑related environment variables:
stty: display or set terminal settings.
locale: view current locale information (locale -a shows supported character sets).
LANG: default locale when no LC_*** variables are set.
LC_ALL: overrides all other LC_*** variables.
LC_COLLATE, LC_CTYPE, LC_MESSAGES, LC_MONETARY, LC_NUMERIC, LC_TIME: locale‑specific settings for sorting, character classification, messages, monetary format, numeric format, and date/time.
Less common but useful variables:

LD_LIBRARY_PATH: colon‑separated directories for the dynamic linker to search for libraries. MANPATH: directories where the man command searches for manual pages. INFODIR: directories for the info command. PAGER: program used to view file contents (e.g., less or more). EDITOR: default text editor (e.g., nano or vi).

Shell positional parameters (used in scripts):
$0, $1 … $9, $*: $0‑$9 correspond to the script name and its arguments (similar to Windows). $#: number of positional parameters. $*: all parameters as a single word. $@: all parameters as separate words.
Special shell variables:
$?: exit status of the last command (0 = success, non‑zero = error).
$$: process ID of the current shell (useful for creating unique temporary filenames).
$!: PID of the most recent background command.
$_: last argument of the previous command.
Effect of quoting on variable assignment:
Double quotes ("): allow variable expansion with $.
Single quotes ('): prevent variable expansion; $ is treated as a literal character.
Backticks (`) or $(…): capture command output and assign it to a variable.

2. Introduction to Bash (Bourne‑Again Shell)

Bash is the default shell on many Linux distributions. Other traditional UNIX shells include tcsh, csh, ash, bsh, ksh, etc. Shell scripts are largely compatible across shells; learning one makes it easy to use others. A shell reads commands, parses them, invokes the kernel or external programs, and returns output. Bash adds pipelines, redirection, powerful scripting features, and job control.

3. Overview of Bash Implementation

Bash uses the GNU Readline library for line editing (vi/emacs style). Its main loop reads user or script input, passes it to the parser, which performs wildcard, alias, arithmetic, and variable expansion, then builds a command structure. Redirection handling and execution are performed by the command executor, which also manages signals and job control. On systems without job‑control support, Bash uses a simplified mechanism.

4. Relationship Between Shell and Environment Variables

Environment variables are set via shell commands and are inherited by child shells. Variables defined in the current shell are called local variables; they may or may not be exported. Exported variables become part of the environment and are visible to all programs launched from that shell.

5. Execution Order of Login Scripts (Bash)

Login Shell
1. /etc/profile – global profile defining PATH, USER, LOGNAME, etc.
2. Scripts in /etc/profile.d/
3. ~/.bash_profile – user‑level login environment.
4. ~/.bashrc – user‑level shell configuration (aliases, functions).
5. /etc/bashrc – global bash configuration.
Non‑Login Shell
1. ~/.bashrc
2. /etc/bashrc
3. Scripts in /etc/profile.d/
Important user‑related files:
/etc/login.defs – defines password policies, expiration, encryption, default home permissions, etc.
/etc/default/useradd – default settings for new users (home directory root, default shell, skeleton files).
/etc/skel – contains default dotfiles (.bashrc, .bash_profile, .bash_logout) copied to a new user's home directory.

6. Practical Uses and Operations on Environment Variables

1. Deleting and replacing variable content
${var#pattern} – delete shortest match of pattern from the beginning.
${var##pattern} – delete longest match from the beginning.
${var%pattern} – delete shortest match from the end.
${var%%pattern} – delete longest match from the end.
${var/old/new} – replace first occurrence of old with new.
${var//old/new} – replace all occurrences of old with new.
2. Setting and substituting variable values
# Single substitution
if [ -z "$a" ]; then a=abc; fi   # ${a:=abc}
# Prompt if unset
${a:?"Variable a must have a value"}
# Temporary substitution
${a:+123}
# Second‑level substitution examples
A=B
a=1
B1="B value"
eval echo \$$A$a > B1.txt   # stores value of B1 in B1.txt
C=`cat B1.txt`
FAIL="echo -e \"
\e[31m${FMSG}\e[0m
\""
FMSG="Error message" && eval ${FAIL}
# Using eval to turn grep output into variable assignments
eval `grep '^.*APPDIR' /etc/tuxconfig`
echo ${APPDIR}

7. Some Built‑In Shell Commands

1. source
# Executes commands from a file in the current shell, making any variable definitions effective.
# Equivalent shorthand: .
source ~/.bash_profile
2. export
# Marks a variable for export to the environment of subsequently executed commands and child shells.
# The variable persists only for the lifetime of the current shell session.
3. env and printenv
# Display all environment variables.
4. set
# Shows and sets local shell variables; running set alone lists all variables (both environment and local).
5. unset
# Removes a variable, whether it is an environment or a local variable.

8. Additional Shell Variable Knowledge

Shell is a weakly typed language; variables need not be declared or initialized.
An array is a named contiguous block of memory, but arrays cannot be exported as environment variables.
Examples of array usage:
  arr=(value1 value2 value3)
  echo ${#arr[*]}   # number of elements
  echo ${arr[0]}    # first element
  echo ${arr[*]}    # all elements
  declare -p arr    # display array definition
Special notes on variable overflow, type representations, and security implications are also discussed.
Source: http://www.178linux.com/8005
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

LinuxUnixBashShell scripting
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.