简体   繁体   中英

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM