Search code examples
loopsfor-loopvariablesarguments

How to use an argument in a loop definition


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


Solution

  • 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