Mastering Safe Variable Expansion with Parameter Indirection
Shell Scripting / Bash Tricks
Mastering Safe Variable Expansion with Parameter Indirection
🧩 The Challenge
You often need to access the value of a variable whose name is stored inside another variable, but using eval is a security risk. Standard syntax fails because the shell does not perform a second level of expansion on the variable name by default.
💡 The Fix
Use bash parameter indirection syntax to dynamically reference variable contents safely without invoking dangerous shell evaluation.
var_name="target"
target="production_db"
echo ${!var_name}
⚙️ Why It Works
The exclamation mark prefix tells the bash shell to interpret the content of the variable as a reference to another variable name, performing an indirect lookup. This avoids the shell injection vulnerabilities associated with eval or arbitrary command execution.
🚀 Pro-Tip: Use the ${!prefix*} syntax to list all variable names currently defined that begin with a specific prefix string.
Linux Tips & Tricks | © ngelinux.com | 7/7/2026
