LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   for loop error (https://www.linuxquestions.org/questions/linux-newbie-8/for-loop-error-805430/)

lipun4u 05-02-2010 05:34 AM

for loop error
 
Why the following code shows error ??


Code:

#!/bin/bash

factorial=1
for (( number = 1; number <= $1; number++ ))
do
        factorial=$[ $number * $factorial ]
done

echo "The factorial of $1 : $factorial"

The error
Quote:

./test1.sh: line 4: ((: number <= : syntax error: operand expected (error token is "<= ")
The factorial of : 1

smoker 05-02-2010 05:40 AM

Where is $1 coming from ?

You can't say something is less than or equal to something else, unless the something else (an operand) exists.

That's apart from the bad assignment in the loop condition.
number=1

catkin 05-02-2010 06:16 AM

FYI $[ <arithmetic expression> ] does work but is no longer documented in the man page; the current method is $(( <arithmetic expression> )).

lipun4u 05-02-2010 02:32 PM

In my book, they say it as advanced for loop. Would please give a better link on this ?

catkin 05-02-2010 03:09 PM

Quote:

Originally Posted by lipun4u (Post 3954920)
In my book, they say it as advanced for loop. Would please give a better link on this ?

for (( )) is the advanced for loop. $(( <arithmetic expresssion> )) is arithmetic expansion (the value of the arithmetic expansion is substituted) and (( <arithmetic expresssion> )) is a conditional construct equivalent to let <arithmetic expresssion>.

smoker 05-02-2010 03:59 PM

The code as you quoted it works IF you supply a number to it.
I repeat - where are you getting $1 from ?

You have to supply that number or there is nothing to compare in the for loop condition.

try running
Code:

test1.sh 15


All times are GMT -5. The time now is 05:19 PM.