Dynamic variables and our friend "if"

Hi guys,

Sorry if it is somewhere in the forum, I've checked for an hour or so with my google friend and can't figure this one out. Not counting the 2 hours I spent yelling at it.

Welcome to BASH + AIX

	$LSLV -l $LV | $GREP -v $LV | $GREP -v "IN BAND" | $AWK '{print $1}' | while read PV; do
		if [ $ARG = "-all" ]; then
			if [ -z "\$${PV}_SIZE" ]; then
				eval ${PV}_SIZE="Some weird calculation"
				eval echo \$${PV}_SIZE
			else
				eval echo \$${PV}_SIZE
			fi
		else
			$ECHO "\t\t|_____ - PV: "`$ECHO $PV | $AWK '{print $1}'`
		fi
	done

In short, I have a list of physical volumes (hdiskX), I want to create a variable hdisk1_size (for example with hdisk1) IF it does not already exists. If it exists, I just want to echo it; only if my $ARG="-all"

I know some part of it works since:

[censored]# PV=hdisk1
[censored]# eval ${PV}_SIZE="test"
[censored]# echo \$${PV}_SIZE
$hdisk1_SIZE
[censored]# eval echo \$${PV}_SIZE
test

I have no idea what is wrong. I've tried wc the amount of letters within the variable, it acts weirdly when put inside the if but works well from the prompt:

# eval echo \$${PV}_SIZE | wc -m
       5

So far I have tried:

[ -z "\$${PV}_SIZE" ]

It always says it's not empty even if not initialized

[ `eval echo \$${PV}_SIZE | wc -m` -eq 1 ]

Note that the above will always be at least 1 (?):

# eval echo \$${UNiX}rAmdOmnEss | wc -m
       1

I've tried a bunch of stuff ... I thought my logic might just be wrong but I can't figure another way of doing it.

Any ideas? :frowning:

Try read instead of eval. It can do the same job -- setting dynamic variable names -- with less doublethink. You can feed it the output of a shell command inside a here-document.

VARIABLENAME="abc_def"

# Sets the variable abc_def
read $VARIABLENAME <<EOF
$(long | complex | command)
EOF

Note that the ending EOF must be at the beginning of the line, not indented.

You can also convert a variable containing a variable name into that varibable's contents with ${!VARNAME}, if you're using BASH or new enough KSH.