Re: Setting a Var= to a variable that is incremented in for loop. (229 Views)
Reply
Contributor
Bob Fohl
Posts: 14
Registered: ‎11-04-1996
Message 1 of 6 (229 Views)

Setting a Var= to a variable that is incremented in for loop.

Example:
i=1
for me in myfile
do
MYVAR$i=`who -u | grep $me'
ME$i=$MYVAR$i < i = i + 1
done

probably over thinking this one...any ideas?

Honored Contributor
Mel Burslan
Posts: 3,214
Registered: ‎08-26-1998
Message 2 of 6 (229 Views)

Re: Setting a Var= to a variable that is incremented in for loop.

you'd rather be looking into array type variables if you are using ksh or posix

example command

# for i in 1 2 3
> do
> let a[$i]=$i+$i
> echo ${a[$i]}
> done
2
4
6

so, yours should look like
i=1
for me in myfile
do
MYVAR[$i]=`who -u | grep $me'
ME[$i]=$MYVAR[$i]
let i=$i+1
done

now you have series of variables as follows
ME[1]="some string"
ME[2]="some other string"
...
ME[n]="yet another string"

to do whatever your heart desires

to reference them, use the following notation:

string=${ME[$i]}

where i is your array index

hope this helps
________________________________
UNIX because I majored in cryptology...
Honored Contributor
Rodney Hills
Posts: 1,679
Registered: ‎09-09-1996
Message 3 of 6 (229 Views)

Re: Setting a Var= to a variable that is incremented in for loop.

Use "eval"

t=`who -u | grep $me`
eval "MYVAR$i=$t"
eval "ME$i=$MYVAR$i"

HTH

-- Rod Hills
There be dragons...
Honored Contributor
Hein van den Heuvel
Posts: 6,588
Registered: ‎05-19-2003
Message 4 of 6 (229 Views)

Re: Setting a Var= to a variable that is incremented in for loop.

Bob, if the prior replies did not help, then be sure to explain in more detail what you are trying to eccomplish. Maybe some sample input/output? What problem are you really trying to solve, once you have that 'who' output in those variables?

- is myfile meant to be a file with names perhaps? In that case check out grep -f and reading its output: who | grep -f myfile | ...

If/when `who -u | grep $me` returns multple lines, should those become individually named/numbered variables?

fwiw,
Hein.
Honored Contributor
Muthukumar_5
Posts: 4,030
Registered: ‎06-09-2004
Message 5 of 6 (229 Views)

Re: Setting a Var= to a variable that is incremented in for loop.

You can use while-do-done loop instead for-do-done.

#!/bin/ksh
i=1

while read me;
do

let VAR[$i]=`who -u | grep $me`
let ME[$i]=${VAR[$i]}
let i=i+1

done < myfile

It will do it.
Easy to suggest when don't know about the problem!
Trusted Contributor
Eknath
Posts: 129
Registered: ‎04-03-2005
Message 6 of 6 (229 Views)

Re: Setting a Var= to a variable that is incremented in for loop.

Hi Bob,

you last line should look like
i=`expr $i +1`

Anyway pls let us know what is your aim behind this. maybe a simple script would solve the problem

Cheers !!!
eknath
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation.