Mastering Bash Parameter Expansion and Special Variables

Direct Variable Expansion

When a shell identifier is assigned a value, it can be referenced during execution by prefixing the name with a dollar sign. The interpreter substitutes the placeholder with its stored content at runtime.

#!/bin/bash
greeting="Hello"
target="World"

echo $greeting
echo $target

Running this snippet outputs the stored strings directly to standard output.

Boundary Awareness

Appending text immediately after a variable reference often causes parsing issues. The shell treats the adjacent characters as part of the identifier itself, leading to an empty result if the combined name is undefined.

#!/bin/bash
prefix="Server"

echo '--- Boundary Test ---'
echo $prefixConfig
echo '--- End ---'

Because prefixConfig was never declared, the output remains blank.

Explicit Delimiters with Braces

The ${identifier} syntax explicitly defines where the variable name ends. This is essential for safe string concatenation and prevents the parser from consuming trailing characters as part of the name.

#!/bin/bash
prefix="Server"

echo '--- Explicit Delimiter ---'
echo "${prefix}Config"
echo '--- End ---'

Here, the shell correctly isolates prefix, substitutes its value, and appends Config to the output.

Command Substitution

Encapsulating a command within $(...) executes the enclosed operation first, then replaces the construct with the resulting standard output. This mechanism is preferred over legacy backticks for readability and nesting support. Note that single quotes inhibit expansion.

#!/bin/bash
echo '--- Execution Flow ---'
echo "Current user context: $(whoami)"
echo "Literal text: $(whoami)"
echo '--- End ---'

Arithmetic Evaluation

Shell environments treat all inputs as character sequences by default. To perform mathematical operations, wrap expressions in $((...)). While $[...] exists in older syntax, modern scripts should rely on the double-parenthesis standard.

#!/bin/bash
operand_a=14
operand_b=3

string_concat="${operand_a}+${operand_b}"
math_result=$((operand_a + operand_b))
legacy_math=$[operand_a + operand_b]

echo "Concatenated: ${string_concat}"
echo "Evaluated: ${math_result}"
echo "Legacy Evaluated: ${legacy_math}"

Reserved Shell Parameters

Bash provides a set of predefined identifiers that capture runtime metadata, argument counts, and process information. These are automatically populated during script execution.

Parameter Description
$0 Name or path of the executing script
$n Positional arguments (1 through 9). For 10+, use ${10}
$# Total number of arguments supplied
$* Expands to all positional arguments
$@ Expands to all positional arguments individually
$? Exit code of the most recently executed foreground command
$$ Process ID of the current shell instance

The following script demonstrates how these values populate when arguments are passed:

#!/bin/bash
echo "================================="
echo "Script path: $0"
echo "Argument 1: $1"
echo "Argument 2: $2"
echo "Total count: $#"
echo "Process ID: $$"
echo "================================="

Executing ./analyze.sh alpha beta correctly maps each parameter to its corresponding reserved variable.

Differentiating $* and $@

While both represent the complete argument list, their behavior diverges when enclosed in double quotes. "$*" merges all inputs into a single string, whereas "$@" preserves each input as a distinct word. This distinction becomes critical in loop constructs.

#!/bin/bash
echo "--- Quoted \$* Behavior ---"
for chunk in "$*"
do
    echo "[${chunk}]"
done

echo "--- Quoted \$@ Behavior ---"
for chunk in "$@"
do
    echo "[${chunk}]"
done

When envoked with multiple values, the first loop executes exactly once with all arguments combined. The second loop iterates individually for each supplied value.

Unlike user-defined variables, reserved parameters do not require or benefit from curly brace encapsulation. Expressions like ${0} or ${$} are syntactically invalid for these cases. Always reference them directly and avoid naming custom identifiers that overlap with reserved tokens.

Tags: bash parameter-expansion command-substitution shell-variables arithmetic-evaluation

Posted on Sat, 01 Aug 2026 17:00:29 +0000 by aalmos