Dynamic Bash Variable Names

| 1 Comment | No TrackBacks

I found myself in the middle of a rather large Bash project a little while back. Basically, I had defined several file paths in variable names and needed to access that information dynamically.

The scenario is this: a value would be supplied by the user, and I had to pull out some hard-wired information based on this value. So, suppose you were writting a script that referenced file types arranged by extenstions and was selected by the user at run time. This would be easily solvable in the following:

#!/usr/bin/env bash

# List of variables maybe in some other file
JPG_FILE_PATH="/opt/path/one"
DOC_FILE_PATH="/opt/path/two"
MP3_FILE_PATH="/opt/path/three"
XLS_FILE_PATH="/opt/path/four"

get_file_path() {
    local ID=${1-''}
    # Sets FILE_PATH to the desired value. If not exist then null.
    FILE_PATH=$(eval "echo \${$(echo ${ID}_FILE_PATH)"-''})
}

get_file_path "MP3" 
echo $FILE_PATH

$ ./test_pre.sh
/opt/path/three

The above snippet -- admittedly a bit humorous -- is very useful in several situations. I happened to use it in creating a shell library of functions and paths that are used by others in the easy creation of scripts around Oracle RDBMS.

No TrackBacks

TrackBack URL: http://www.secnix.com/mt-cgi/mt-tb.cgi/7

1 Comment

Thanks for this. I've spent hours trying to find the way to have a variable in a variable's name. I've read other posts saying (translated) "eval FILE_PATH=${!ID}_FILE_PATH" or something along those lines, but that fails to work for me. Any ideas why? Anyway, thanks again.

Leave a comment

About this Entry

This page contains a single entry by Justin published on October 28, 2008 9:05 PM.

Red Hat Certified Engineer was the previous entry in this blog.

My new iMac is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Pages