Course contentsShow
← Linux
Lesson 118 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Dynamic Variable Referencing

Implement indirect variable access patterns for flexible script configurations.

In this lesson, you will learn how to access the value of a variable whose name is stored inside another variable, allowing for highly flexible script configurations.

The Concept of Indirection

Normally, when you type echo $NAME, the shell looks at the variable NAME and prints its value. But what if the name of the variable you want to use is itself a value stored in a string? This is called Dynamic Variable Referencing (or indirect expansion).

Imagine you are building a script that manages different environment settings (like dev, prod, or test). You might have variables like db_dev="localhost" and db_prod="10.0.0.5". If you have a variable target="dev", you don't want to write if/else statements for every environment. Instead, you want to point to the variable named after the target.

Implementing Indirect Access

In Bash, the most common way to achieve this is using the ${!variable} syntax. The exclamation mark tells the shell: "Don't give me the value of this variable directly; use its value as the name of another variable, and give me that one's value instead."

Consider this example:

# Configuration variables
server_dev="192.168.1.5"
server_prod="10.0.0.10"

# User-defined selection
target="dev"

# Building the reference dynamically
# The '!' tells bash to look up the variable named inside 'target'
reference="server_$target"
echo "Connecting to: ${!reference}"

In the code above, ${!reference} resolves in two steps:

  1. It sees reference holds the string server_dev.
  2. It then looks up the value stored in the variable named server_dev, resulting in 192.168.1.5.

This pattern is incredibly powerful for writing modular scripts where the behavior changes based on external inputs or dynamic environment states. You can loop through a list of configurations, process them, and switch between them without hardcoding every possible pathway into your logic.

Key Takeaway: Use the ${!variable} syntax to perform indirect expansion, allowing your scripts to treat variable names as data and reference them dynamically during execution.