0
abc=( "one" "two" "three" )

for((i=0; i<${#abc[@]}; i++))
{
 
   xyz$i="hello"  --- this is giving me error as no such file or directory

   eval xyz$i="hello" --- this is working fine and solving my above error

 eval xyz$i="hello ${abc[$i]}"  --- this line is again giving me error as no such file or directory

}

what is the correct way i can assign the value

Biffen
  • 6,249
  • 6
  • 28
  • 36
rock
  • 11
  • 4
  • 1
    A parameter explansion is not allowed to the left of a substitution. You could use `eval` (works, if you do it right, but **not recommended**), [indirect parameter expansion](https://stackoverflow.com/questions/8515411/what-is-indirect-expansion-what-does-var-mean), a [nameref](https://stackoverflow.com/questions/49179596/making-a-nameref-a-regular-variable-in-bash) (see the bash man-page and search for _nameref_) or make `xyz` an [associative array](https://stackoverflow.com/questions/1494178/how-to-define-hash-tables-in-bash/3467959#3467959). – user1934428 Apr 22 '22 at 07:01
  • 1
    The "correct" way is to use a language with the data structures you need, rather than trying to simulate them in `bash`. – chepner Apr 22 '22 at 12:31

1 Answers1

0

You can use bash's printf builtin with -v option:

#!/bin/bash

abc=( "one" "two" "three" )

for ((i=0; i<${#abc[@]}; i++)); do
    printf -v xyz$i 'hello %s' "${abc[i]}"
done

echo "$xyz0"
echo "$xyz1"
echo "$xyz2"
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17