[Techtalk] using variables as part of variable name

dominik schramm dominik.schramm at gmxpro.net
Sat May 15 10:40:25 EST 2004


Hi,

"Dennis Wheeler" <dennisw at vidiator.com> writes:

> src_da=foo1
> src_bi=bar1
>
> tgt_da=foo2
> tgt_bi=bar2
> [...]
> for var in da fe gu vi
> do
>     cp $src_$var $tgt_$var
> done

Another possibility -- besides eval, see Almut's post -- to achieve 
your goal is using arrays. Thus, you can number your variables, which
might save you some typing:

  src[0]=foo1
  src[1]=bar1

  tgt[0]=foo2
  tgt[1]=bar2

or shorter:

  src=("foo1" "bar1")
  tgt=("foo2" "bar2")

  for i in `seq 0 $((${#src[*]} - 1))`
  do
    cp ${src[$i]} ${tgt[$i]}
  done

or even shorter, but slightly more complicated:

  pairs=("foo1:foo2" "bar1:bar2" "xy1:xy2")

  for i in `seq 0 $((${#pairs[*]} - 1))`
  do
    cp ${pairs[$i]%:*} ${pairs[$i]#*:}
  done

Note that without modifications this only works if there are no colons
in the source or target values.

Short explanation: 
 ${#x[*]} is the number of elements of array x

 $(($x - 1) subtracts 1 from $x

 seq 0 $x returns all the numbers from 0 to $x (boundaries included)

 ${x%:*} cuts off everything from $x from ":" to the right end

 ${x#*:} cuts off everything from $x from the beginning up to and 
         including ":"

See the bash manual page (the paragraph titled "Arrays") for details
if you're interested in arrays.

> Sorry if I'm posting this to the wrong list -- if someone moves 
> this to another list can you please cc me the replys?

I think this post is perfectly okay on this list.

hope this helps a little
dominik



More information about the Techtalk mailing list