Linux Shell Variables: A Comprehensive Guide from Beginner to Expert

Linux Shell Variables: A Comprehensive Guide from Beginner to Expert

Note: This article is an original work by Liu Feng from Anyatech. Please respect intellectual property rights. When sharing, please indicate the source. No plagiarism, adaptation, or unauthorized reproduction is accepted.

Introduction

In the Linux world, Shell variables are like the “soul of scripts”.

They may seem simple, but they carry out core tasks such as data storage, environment configuration, and logical control.

Many people use them, but may not truly understand their intricacies.

This article will take you from basic definitions to advanced operations, thoroughly unraveling the mysteries of Shell variables, helping you achieve a deeper understanding in daily operations and script writing.

01

What are Shell Variables?

Essentially, a Shell variable is a named container used to store a single data value within a Shell process.

It consists of a variable name (Variable Name) and a value (Value), which are associated through an assignment operation.

The Shell references the stored value through the variable name, enabling temporary storage, transmission, and processing of data.

All Shell variable values are treated as strings internally.

Even if we assign a numeric value to a variable (e.g., VAR=123), the Shell will initially treat it as the string “123” and only temporarily interpret it as a number during arithmetic operations.

[Experiment 1-1: Verify the String Nature of Variables]

# 1. Define a numeric variable and a string variable
NUMERIC_VAR=123
STRING_VAR="123"

# 2. Concatenation operation; if both are strings, it should concatenate successfully
CONCAT_RESULT=$NUMERIC_VAR$STRING_VAR
echo "Concatenation result: $CONCAT_RESULT"
# Result output:
# Concatenation result: 123123

# 3. Use string comparison
if [ "$NUMERIC_VAR" = "$STRING_VAR" ]; then
    echo "Conclusion: The variable NUMERIC_VAR is treated as a string during comparison."
fi
# Result output:
# Conclusion: The variable NUMERIC_VAR is treated as a string during comparison.

02

Variable Types and Scope

Based on their scope and characteristics, Shell variables can be mainly divided into the following categories:

Local Variables

  • Scope

    Effective only within the current Shell instance.

    They are not inherited by any child processes created by the current Shell.

  • Usage

    Primarily used for temporary data storage within scripts, loop counters, private variables within functions, etc.

    This is the most common type of variable.

Environment Variables

  • Scope

    Effective not only in the current Shell instance but also extends to all child processes started by the current Shell through inheritance.

  • Usage

    Used to set the runtime environment for processes, such as configuring program search paths (PATH), specifying user home directories (HOME), etc.

[Experiment 2-1: Verify the Scope Differences Between Local and Environment Variables]

# 1. Define a local variable and an environment variable in the current Shell (parent process)
LOCAL_VAR="I am local to the parent shell."
export ENV_VAR="I am an environment variable, visible to children."

echo "--- In Parent Process ---"
echo "Local Variable: $LOCAL_VAR"
echo "Environment Variable: $ENV_VAR"

# --- Result output ---
--- In Parent Process ---
Local Variable: I am local to the parent shell.
Environment Variable: I am an environment variable, visible to children.

# 2. Start a new Bash Shell (child process) to simulate the child process environment
#    -c option followed by the command will be executed in this new shell
bash -c '
  echo ""
  echo "--- In Child Process ---"
  echo "Attempting to access Local Variable: $LOCAL_VAR"
  echo "Attempting to access Environment Variable: $ENV_VAR"
'
# --- Result output ---
--- In Child Process ---
Attempting to access Local Variable: 
Attempting to access Environment Variable: I am an environment variable, visible to children.

Positional Parameters:

  • Definition

    When executing a Shell script, the parameters passed to the script are assigned in order to a series of special read-only variables, known as positional parameters.

  • Naming

    $0 represents the name of the script itself, $1 represents the first parameter, $2 represents the second parameter, and so on. $# represents the total number of parameters passed, while $* and $@ represent the collection of all parameters (the two have subtle differences in specific situations).

Special Variables

  • Definition

    The Shell has predefined a series of variables with special meanings, used to report the Shell’s state or the execution result of the last command.

  • Example

    $? stores the exit status code of the last command executed (0 indicates success, non-zero indicates failure), and $$ stores the PID (process ID) of the current Shell process.

[Experiment 2-2: Demonstrate Positional Parameters and Special Variables]

# 1. Create a script file named test_script.sh
cat > test_script.sh <<'EOF'
#!/bin/bash
echo "Script Name (\

Leave a Comment