Home > database >  How to use an argument in a loop definition
How to use an argument in a loop definition

Time:03-05

thanks for your help. What a I doing wrong, here ? I want the numeric answer to be used in a loop but it does not return what I expected :

if [ "$#" -eq 0 ]; then
echo -n "Enter the number: "
read answer
else
  answer=( "$@" )
fi
for i in {1..$answer} ; do echo ${i}; done

When executed, I have this:

me@local misc]$ ./test.sh
Enter the number: 5
{1..5}

I expected the echo to return 1 2 3 4 5

CodePudding user response:

With no proposed answer I decided to switch to bash with that syntax that works (though it bothers me)

for (( i=1 ; i<=${answer} ; i  ));

CodePudding user response:

You can also do it like:

if [ "$#" -eq 0 ]; then
echo -n "Enter the number: "
read answer
else
        answer=( "$@" )
fi
for i in $(seq 1 $answer) ; do echo ${i}; done
  • Related