Class 16 of 37 • Shell Scripting Fundamentals \t\t\t\t

Variables in Linux Shell Scripting - System, User & Environment Variables

Variables are an essential building block of every programming and scripting language. In Linux, a variable is a named storage pointer referencing a block of memory whose stored content can be read or modified during program execution. Unlike statically typed languages like C, Java, or C++, Linux shell scripting is dynamically and untyped: variables hold ASCII text strings by default, which can be interpreted as integers depending on the arithmetic context. Linux distinguishes between two broad categories of variables: System (Environment) Variables and User-Defined Variables.

1. System (Environment) Variables

An environment variable is a global setting managed by the Linux operating system kernel and shell session. They are available to any child process or executable program invoked from the shell. By convention, system environment variables are named in UPPERCASE letters. The table below lists the most important system variables:

Variable

Check Value Command

Descriptions

BASH_VERSION

echo $BASH_VERSION

Holds the version string of the currently running Bash instance.

HOSTNAME

echo $HOSTNAME

The networked hostname assigned to your Linux machine.

CDPATH

echo $CDPATH

A colon-delimited search path list for the cd command.

HISTFILE

echo $HISTFILE

Path to the file where interactive command history is saved (e.g., ~/.bash_history).

HISTFILESIZE

echo $HISTFILESIZE

The maximum number of lines saved in the history file on disk.

HISTSIZE

echo $HISTSIZE

The number of remembered commands in active terminal memory (default is typically 1000).

HOME

echo $HOME

The absolute path to the home directory of the current user (e.g., /home/student or /root).

IFS

echo "$IFS"

Internal Field Separator used for word-splitting expansions (default: space, tab, newline).

LANG

echo $LANG

System locale, character encoding, and language configuration (e.g., en_US.UTF-8).

PATH

echo $PATH

Colon-separated directory list searched by the shell to find executable binaries.

PS1

echo "$PS1"

Primary interactive shell command-line prompt string format.

TMOUT

echo $TMOUT

Idle timeout in seconds for automatic logout or read command termination.

TERM

echo $TERM

Type of terminal emulation currently connected (e.g., xterm-256color).

SHELL

echo $SHELL

Absolute path to the user's default login shell interpreter (e.g., /bin/bash).

PWD

echo $PWD

Print Working Directory: the current directory path of the active shell process.

USER / USERNAME

echo $USER

The login name of the current authenticated system user.

2. User-Defined Variables

Shells allow programmers to create customized local variables for storing numbers, strings, and command outputs. By convention, user-defined variables are named in lowercase or camelCase to avoid accidental collisions with system environment variables.

Naming Rules & Assignment Syntax

  • Variable names can contain letters (a-z, A-Z), numbers (0-9), and underscores (_).
  • Names cannot start with a number (e.g., 1var is invalid).
  • Variable names are case-sensitive: $Count, $COUNT, and $count are three distinct variables.
  • CRITICAL RULE: There must be NO SPACES around the equal sign (=)!
# CORRECT: No spaces around '='
count=10
company='Veewom Technology'
pi=3.14159

# INCORRECT (Will trigger "command not found" errors!):
count = 10        # Error!
company = 'Veewom' # Error!

Referencing Variable Values

To extract or print the value of a variable, prefix its name with the dollar symbol ($) or wrap it in curly braces (${}):

#!/bin/bash
name="Linus Torvalds"
project="Linux Kernel"

echo "Creator: $name"
echo "Project: ${project}_v6.x"  # Braces protect the variable name from following text

3. Read-Only Variables & Unsetting Variables

You can protect sensitive variables from accidental overwrite or remove variables from memory when no longer needed:

#!/bin/bash
# 1. Read-Only Variable (Constant)
readonly API_PORT=8080
echo "Port: $API_PORT"

# Trying to reassign a readonly variable causes a bash error:
# API_PORT=9000   # bash: API_PORT: readonly variable

# 2. Unsetting (Deleting) a variable
temp_data="Temporary buffer"
echo "Before unset: $temp_data"

unset temp_data   # Removes temp_data from memory
echo "After unset: $temp_data" # Outputs an empty blank line

4. Exporting Variables to Child Processes

By default, user-defined variables are local to the current script or shell process. If your script launches a child script or subshell, that child cannot see your variables unless you export them:

#!/bin/bash
# Local variable: Only visible inside this script
LOCAL_VAR="Visible only here"

# Exported environment variable: Inherited by child processes and scripts
export APP_ENV="production"
export DATABASE_URL="mysql://localhost:3306/veewom_db"

# Now any child script executed here can read $APP_ENV
./run_service.sh

5. Quoting Rules in Shell Scripting

Quote Type

Behavior

Example with user="Alice"

Double Quotes ("...")

Permits variable expansion ($) and command substitution ($()), but prevents word-splitting.

echo "Hello $user" → "Hello Alice"

Single Quotes ('...')

Strictly literal. Disables all expansions, dollar signs, and escapes.

echo 'Hello $user' → "Hello $user"

Backticks / $()

Command substitution: executes the inner command and replaces with its stdout.

today=$(date +%Y-%m-%d)

6. Parameter Substitution Default Values

Bash provides convenient shorthand to assign fallbacks when variables might be unset:

  • ${var:-fallback} : If var is unset or null, return fallback (does not assign).
  • ${var:=fallback} : If var is unset, return fallback AND assign it to var.
  • ${var:?error_msg} : If var is unset, print error_msg and abort execution.

Lab Practice: System Audit & Environment Profiler

Problem: Write a comprehensive shell script that reads system variables, prompts for user parameters with defaults, and prints an formatted system audit report.

#!/bin/bash
# sys_profiler.sh: System audit script demonstrating variables

# Read system variables
cur_user=${USER:-"Unknown User"}
cur_shell=${SHELL:-"/bin/sh"}
cur_home=${HOME:-"/root"}
cur_host=${HOSTNAME:-"localhost"}
cur_path=${PATH}

echo "============================================="
echo "       LINUX SYSTEM PROFILE REPORT"
echo "============================================="
echo "Date & Time    : $(date)"
echo "Current User   : $cur_user"
echo "Host Machine   : $cur_host"
echo "Home Directory : $cur_home"
echo "Active Shell   : $cur_shell"
echo "Working Dir    : $PWD"
echo "---------------------------------------------"

# Prompt user with parameter substitution default
read -p "Enter backup directory [Default: /tmp/backup]: " backup_dir
target_dir=${backup_dir:-"/tmp/backup"}

echo "Configured Backup Target: $target_dir"
echo "============================================="

Frequently Asked Questions (FAQs)

The shell uses whitespace as a separator between command names and arguments. Writing count = 10 tells the shell to find a command called count with arguments = and 10. Writing count=10 without whitespace correctly signals an assignment expression.
Double quotes ("$var") evaluate the variable and substitute its contents while protecting spaces. Single quotes ('$var') preserve the exact literal string characters without interpreting the $ symbol.
Normal variables exist only in the current shell. The export command exports the variable to the shell's environment table, making it accessible to all future child scripts, subprocesses, and commands.
Use the readonly built-in command: readonly MAX_USERS=50. Attempting to reassign or unset a read-only variable will produce a shell permission error.

Next Step in Your Linux Learning Path:

Format terminal output, escape characters, and colorize logs in Class 17: Echo Command.

Continue to Class 17: Echo Command → Previous: ← Shell Comments | Full Syllabus

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!