Simpler Navigation coming for Servers and Operating Systems
Coming soon: a much simpler Servers and Operating Systems section of the Community. We will combine many of the older boards, and you won't have to click through so many levels to get at the information you need. If you are looking for an older board and do not find it, check the consolidated boards, as the posts are still there.
Languages and Scripting
cancel
Showing results for 
Search instead for 
Did you mean: 

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

Bob Fohl
Contributor

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?

5 REPLIES
Mel Burslan
Honored Contributor

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...
Highlighted
Rodney Hills
Honored Contributor

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...
Hein van den Heuvel
Honored Contributor

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.
Muthukumar_5
Honored Contributor

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!
Eknath
Trusted Contributor

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