The Problem

Recently I was developing some shell scripts (ShellScripts on GitHub) and needed to reference a variable that had a dynamically created name. Essentially I had some values defined in a properties file that were named "client_1, client_2, ... , client_N" where N is not known until run-time of the script. I could easily build the names of all of the variables in a string, but ho do I then convert that String name into an actual variable? After searching high and low, I found the solution.

The Solution

The first step is to create a variable that holds the dynamically created varialbe name:
varName=client_$n

To get the name of the newly created variable, you access it like this:
${varName}

To get the value of the newly created variable, you access it like this:
${!varName}

Reference



Published

31 July 2012

Tags