BashScripts.org
http://bashscripts.org/forum/

Nested variable within a variable
http://bashscripts.org/forum/viewtopic.php?f=8&t=1485
Page 1 of 1

Author:  jfinn [ Wed Nov 09, 2011 10:34 am ]
Post subject:  Nested variable within a variable

Below is my broken code. The problem is trying to read the original values.
Code:
x=1
y=2
z=3

for var in x y z
do
     if [ -n ${$var} ]
     then
          echo "$var: ${$var}"
     fi
done

Desired output:

x: 1
y: 2
z: 3

Author:  Keith Hedger [ Wed Nov 09, 2011 11:05 am ]
Post subject:  Re: Nested variable within a variable

Indirect variables are referenecd via the ! ie:
Code:
#!/bin/bash -e
x=1
y=2
z=3

for var in x y z
do
     if [ -n ${!var} ]
     then
          echo "$var: ${!var}"
     fi
done

gives
Code:
x: 1
y: 2
z: 3

Author:  jfinn [ Wed Nov 09, 2011 1:25 pm ]
Post subject:  Re: Nested variable within a variable

That helps a lot, thanks! Only problem is the -n doesn't seem to be working properly. For instance if you didn't specify 3 for variable z the output would be:

x: 1
y: 2
z:

I don't want the empty variables to print.

Author:  jfinn [ Wed Nov 09, 2011 1:37 pm ]
Post subject:  Re: Nested variable within a variable

As a workaround I just swapped out the -n piece for

Code:
if [ "${!var}" != "" ]


Just curious why the -n didn't work.

Author:  Watael [ Wed Nov 09, 2011 2:26 pm ]
Post subject:  Re: Nested variable within a variable

hi,

because you don't use enough quotes :
Code:
x=1 y=2
for var in x y z
do [ -n "${!var}" ] && echo "$var = ${!var}"
done

Author:  Keith Hedger [ Wed Nov 09, 2011 4:06 pm ]
Post subject:  Re: Nested variable within a variable

from the abs guide
Quote:
-n

string is not null.

Caution

The -n test requires that the string be quoted within the test brackets. Using an unquoted string with ! -z, or even just the unquoted string alone within test brackets (see Example 7-6) normally works, however, this is an unsafe practice. Always quote a tested string. [1]


so just use if [ -n "${!var}" ]

Author:  jsz [ Wed Nov 09, 2011 7:52 pm ]
Post subject:  Re: Nested variable within a variable

test(0)'s default flag is -n, so you don't have to specify it.

And since you're writing in bash(1), then just use the [[ ... ]] syntax:
Code:
if [[ ${!var} ]]; then


You don't have to quote the left-hand side.

Page 1 of 1 All times are UTC - 6 hours
© 2000, 2002, 2005, 2007 phpBB Group • http://www.phpbb.com