Reputation: 93
#!/bin/bash
n=1
while (( $n <= 5 ))
do
num$n=`echo "$n"`
n=$(( n+1 ))
done
echo "$num1"
ok so what I am trying to do is create a while loop that will create variables and just put something into it in this case its just the value of n but i cant get it to do this!
so basically it will create num1, num2, num3 and so on
echo "$num1"
echo "$num2"
echo "$num3"
should display
1
2
3
but i keep getting an error am i missing something here cause it shouldnt be anything crazy to do this...
Upvotes: 0
Views: 419
Reputation: 1865
Try with
#!/bin/bash
n=1
while (( $n <= 5 ))
do
eval num$n=`echo "$n"`
n=$(( n+1 ))
done
echo "$num1"
echo "$num2"
echo "$num3"
The problem here is that bash is trying to evaluate num$n as a command, which does not exist, so the error.
Upvotes: 3
Reputation: 531095
Don't dynamically create numbered variable names like this; use an array.
n=1
while (( $n <= 5 )); do
nums[$n]=$n # No need to execute $(echo ...)
n=$((n+1))
done
echo "${num[1]}"
echo "${num[2]}"
echo "${num[3]}"
Upvotes: 0