Expand Nested Bash Variables

Consider the following Bash script:

RICK="Rick Sanchez"
echo $TINY_RICK 

We nest a variable named “RICK” within another variable named “TINY_RICK”, and as you can probably guess the output of the script will not be the expected “Rick Sanchez”.

This is because Bash will not recursively resolve variables while evaluating a string, so the output will be:

➜ ~ sh ./scripts.sh


We can in fact ask bash to resolve a nested variable using the following syntax [notice the exclamation mark (!) prefixing the variable name]:

echo "${!TINY_RICK}" # Resolve the nested variable name

But this is not enough. Remember that our variable contains a literal “$” symbol? Although this is valid syntax, Bash will ignore it as a reference to a variable. So using the exclamation mark (!) will work only if the nested value is the name of the variable sans-prefix.

In order to solve this, we simply strip the first character from the value:

TINY_RICK="${TINY_RICK:1}" # String the first character - a $
echo "${!TINY_RICK}" # Resolve the nested variable name 

and now our script:

RICK="Rick Sanchez"
echo ${!TINY_RICK} 

Will output “Rick Sanchez”!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s