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.
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 |
|---|---|---|
|
|
Holds the version string of the currently running Bash instance. |
|
|
The networked hostname assigned to your Linux machine. |
|
|
A colon-delimited search path list for the |
|
|
Path to the file where interactive command history is saved (e.g., |
|
|
The maximum number of lines saved in the history file on disk. |
|
|
The number of remembered commands in active terminal memory (default is typically 1000). |
|
|
The absolute path to the home directory of the current user (e.g., |
|
|
Internal Field Separator used for word-splitting expansions (default: space, tab, newline). |
|
|
System locale, character encoding, and language configuration (e.g., |
|
|
Colon-separated directory list searched by the shell to find executable binaries. |
|
|
Primary interactive shell command-line prompt string format. |
|
|
Idle timeout in seconds for automatic logout or |
|
|
Type of terminal emulation currently connected (e.g., |
|
|
Absolute path to the user's default login shell interpreter (e.g., |
|
|
Print Working Directory: the current directory path of the active shell process. |
|
|
The login name of the current authenticated system user. |
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.
a-z, A-Z), numbers (0-9), and underscores (_).1var is invalid).$Count, $COUNT, and $count are three distinct variables.=)!# 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!
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
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
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
Quote Type |
Behavior |
Example with |
|---|---|---|
Double Quotes ( |
Permits variable expansion ( |
|
Single Quotes ( |
Strictly literal. Disables all expansions, dollar signs, and escapes. |
|
Backticks / |
Command substitution: executes the inner command and replaces with its stdout. |
|
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.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 "============================================="
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.
"$var") evaluate the variable and substitute its contents while protecting spaces. Single quotes ('$var') preserve the exact literal string characters without interpreting the $ symbol.
export command exports the variable to the shell's environment table, making it accessible to all future child scripts, subprocesses, and commands.
readonly built-in command: readonly MAX_USERS=50. Attempting to reassign or unset a read-only variable will produce a shell permission error.
Format terminal output, escape characters, and colorize logs in Class 17: Echo Command.
Continue to Class 17: Echo Command → Previous: ← Shell Comments | Full Syllabus