Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The :- operator is a shell parameter expansion modifier used to provide a default value during variable substitution. It evaluates the state of a parameter and returns a specified fallback string if the parameter is either unset or null (an empty string).

Syntax

${parameter:-word}
  • parameter: The name of the variable being evaluated.
  • word: The fallback expression. This is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion before being returned.

Evaluation Mechanics

The operator evaluates the parameter against three distinct memory states:
  1. Set and Not Null: If parameter contains a value of length > 0, the expansion yields the value of parameter. The word is ignored.
  2. Unset: If parameter has not been declared in the current shell execution environment, the expansion yields the evaluation of word.
  3. Null: If parameter is declared but contains an empty string (""), the expansion yields the evaluation of word.
Note: The :- operator is strictly a substitution mechanism. It does not assign the evaluated word back to the parameter. To perform substitution and assignment simultaneously, the := operator is used.

State Visualization


# State 1: Set and not null
VAR="data"
echo "${VAR:-fallback}"  

# Output: data


# State 2: Unset
unset VAR
echo "${VAR:-fallback}"  

# Output: fallback


# State 3: Null (empty string)
VAR=""
echo "${VAR:-fallback}"  

# Output: fallback

Technical Distinction: :- vs -

The inclusion of the colon (:) dictates how the shell handles null values.
  • ${parameter:-word}: Tests for both unset and null.
  • ${parameter-word}: Tests strictly for unset. If the parameter is null, the shell considers it a valid state and returns the empty string.
VAR=""


# Omitting the colon treats the null variable as valid
echo "${VAR-fallback}"   

# Output: (empty string)


# Including the colon treats the null variable as invalid
echo "${VAR:-fallback}"  

# Output: fallback
Master Bash with Deep Grasping Methodology!Learn More