Re: for loop variable

On Thu, 20 Sep 2007 16:20:30 -0700, explor wrote:

On Sep 20, 3:48 pm, Kenan Kalajdzic <ke...@xxxxxxx> wrote:
explor <bhaves...@xxxxxxxxx> wrote:
Hi Gurus,
I am trying to write a script which goes to each box and grabs the
netstat # and present it in a file. The issue for me is the
LOGGED_USERS_${HOST} which isn't working. can you please guide me how
should i get this working. The variable isn't expanding correctly in
for loop.

for HOST in 7 8 9 10 11 12 13
LOGGED_USERS_${HOST}=$(ssh mailt${HOST} "netstat -an | grep

You need an "eval" in front of the variable name:

eval LOGGED_USERS_${HOST}=$(ssh ...)


Kenan Kalajdzic

Thanks..but i still have an issue

for HOST in 7 8 9 10 11 12 13
eval LOGGED_USERS_${HOST}=$(ssh mailhost${HOST} "netstat -an | grep
ESTABLISHED | grep ".143" |wc -l | tr -d ' '") done

print "Users Logged in Mailt7: ${LOGGED_USERS_$HOST}"

./[24]: "Users Logged in Mailt 7: ${LOGGED_USERS_
$HOST}": bad substitution

Well, the HOST variable is probably not set on line 24 in the way that
you expect.

However the main problem is that you have the wrong syntax. You need

eval print "Users Logged in Mailt7: \${LOGGED_USERS_$HOST}"

You may be able to avoid these eval statements if you can use an array
instead. Also you can probably use grep to count, rather than using wc
and tr, and you probably want to quote the "." in the pattern to grep
or else use fgrep, or else use a colon which is the actual character I
think you want to match.

CMD="netstat -tn | grep -c ':143.*ESTABLISHED'"
for HOST in 7 8 9 10 11 12 13
LOGGED_USERS[${HOST}]=$(ssh mailhost${HOST} "$CMD" )
print "Users Logged in Mailt7: ${LOGGED_USERS[$HOST]}"