/ Show and Tell

Variable Variable Names in Bash

Yo dawg, I heard you like variables. So I put a variable in your variable so you can variable while you variable!

Now that we've got that out of the way, time for the good stuff.

I ran into this problem recently while writing a script to either take a file to read in at runtime OR ask the user for the information after the script is called. Sounded easy enough, but I ran into a snag.

I wanted a unified set of variables. In this case it was 16 unique items that would be implanted into the HTML output of the script. The read_file function would read 16 lines of a supplied file and assign each line to a variable in the form of v#. The issue with this was I would need an assignment statement that had variables on both sides of the equal sign.

#!/bin/bash -
x=1
while read line
do
	v$x=$line
	x=$(($x+1))
done < $1

This looked right, at least to my eyes, but is in fact going to try to run a command called v1, v2, v3, and so on. Not quite what I wanted.

After much Googleing, I found references to an Indirect Variable and 'eval'. I had found my silver bullet.

while read line
do
	eval v${x}=${nline}
	x=$(($x+1))
done < $1

I'm sure there are multiple ways (and probably 'better' ways) to tackle this problem, but I was determined to make it work the way I wanted it to and do hope this helps out a fellow stubborn bash scripter.