LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Bash Shell Scripting Dynamic Variable naming question (http://www.linuxquestions.org/questions/programming-9/bash-shell-scripting-dynamic-variable-naming-question-526451/)

ZuG 02-07-2007 01:47 PM

Bash Shell Scripting Dynamic Variable naming question
 
Hello,

I'm trying to name a variable dynamically such that the name is the contents of another variable plus some text.

Example:

variable $SITE=http://10.0.0.1
I want to create variable called "http://10.0.0.1DOWN" using the $SITE variable and then assign some value to it.

Something like:

"$SITE"DOWN=no

but of course that doesn't work. I get
bash: http://10.0.0.1DOWN=no: command not found.

How do I get it right?

wjevans_7d1@yahoo.co 02-07-2007 03:37 PM

Know two things.

First, a symbol in bash may not contain colons, slashes, or periods. Period. I recommend you change them all to underscores, or get rid of them altogether.

Second, bash can get confused if you do something like

$SYMBOL1=no

no matter what the current value of $SYMBOL is. You can get around that by using the "set" command (or the "export" command if you wish this symbol to be accessible by programs you run after that).

I recommend you play with something like this:

Code:

NEWSITE=$(echo $SITE | sed -e 's/[^A-Za-z0-9]/_/g' -e 's/$/DOWN/')
set ${NEWSITE}=no

Hope this helps.

jlliagre 02-07-2007 03:39 PM

This is generally doable, but you first need to use a valid variable name, and "http://10.0.0.1DOWN" is not.

That one would work:
Code:

$ SITE=http_10_0_0_1
$ eval ${SITE}DOWN=no
$ eval echo ${SITE}DOWN
http_10_0_0_1DOWN
$ eval echo \$${SITE}DOWN
no
$ echo $http_10_0_0_1DOWN
no



All times are GMT -5. The time now is 05:06 AM.