Assign variables inside for loops

2019-03-05 04:10发布

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

2条回答
神经病院院长
2楼-- · 2019-03-05 04:21

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
查看更多
走好不送
3楼-- · 2019-03-05 04:44
for (( i =0;i<2;i++ )); do
  printf -v "p$i" '%s' "pra$i"
done
查看更多
登录 后发表回答