Site icon New Generation Enterprise Linux

Stop running into shell variable nightmares with indirect expansion

Shell Scripting / Bash Tricks

Stop running into shell variable nightmares with indirect expansion

🧩 The Challenge

Dealing with dynamic variable names in scripts is a nightmare when you have to evaluate a variable that contains the name of another variable. I spent an entire afternoon once trying to debug a loop that was just concatenating strings instead of actually grabbing the value I wanted.

💡 The Fix

Use the exclamation mark syntax to perform indirect expansion so the shell resolves the reference before doing anything else. It saves you from writing messy eval statements that are basically just security holes waiting to happen.

var_name="MY_TARGET"
MY_TARGET="DataValue"
echo "${!var_name}"

⚙️ Why It Works

By putting the exclamation mark inside the curly braces, you tell Bash to look at the value of the variable first and then treat that value as the name of the variable you actually want to access. This avoids the dangerous overhead of spawning a subshell or using eval to parse code on the fly.

🚀 Pro-Tip: Don’t get cute and try to nest these too deeply, or your scripts will become unreadable to anyone else on the team.

Linux Tips & Tricks | © ngelinux.com | 10/14/2026

0 0 votes
Article Rating
Exit mobile version