prabhu
prabhu

Reputation: 321

Assign variables inside for loops

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

Upvotes: 0

Views: 106

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295288

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

Upvotes: 0

fedorqui
fedorqui

Reputation: 289505

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

Upvotes: 3

Related Questions