Assign variables inside for loops

回眸只為那壹抹淺笑 提交于 2019-12-02 18:19:12

问题


I am trying a small code which is

for(( i =0;i<2;i++ )); do p$i=\"pra$i\"; done

expected output is: Variable must be assigned

p0="pra0"
p1="pra1"

But bash is taking that as command and am getting output as

p0="pra0": command not found
p1="pra1": command not found

Thanks


回答1:


Use eval to have the value evaluated and stored as you want:

$ for(( i =0;i<2;i++ )); do eval p$i=\"pra$i\"; done
$ echo $p1
pra1

Or better with declare (thanks chepner as always!):

$ for(( i =0;i<2;i++ )); do declare "p$i=pra$i"; done
$ echo $p1
pra1



回答2:


for (( i =0;i<2;i++ )); do
  printf -v "p$i" '%s' "pra$i"
done


来源:https://stackoverflow.com/questions/22036966/assign-variables-inside-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!