'Not able to assign value to variable$i in shell script

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



Solution 1:[1]

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"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 M. Nejat Aydin