BASH: Factorial using FOR loop not working

July 15, 2010 at 06:26:26
Specs: AIX

I am trying to run the factorial script but it’s not working.

The code is mentioned below:
/home/gc> cat
# using one command line parameter

for (( number = 1; number <= $1 ; number++ ))
factorial=$[ $factorial * $number ]
echo The factorial of $1 is $factorial
/home/gc> bash -x 5
+ factorial=1 syntax error near unexpected token `((' line 5: `for (( number = 1; number <= $1 ; number++ ))'

Can anyone please help?


See More: BASH: Factorial using FOR loop not working

Report •

July 15, 2010 at 07:26:09
Your script works for me. I am running a bash shell on Solaris 9. Try this and see what happens:

factorial=$(( factorial * number ))

Report •

July 15, 2010 at 09:00:35
Ok, I've got the reason; it's the bash shell version. I was running the script in an old bash version. I found a link where this was stated. It was mentioned that 'seq' command can be used instead but even that is not recognized on my bash.

I am using GNU bash, version 1.14.5(1)

Can anyone suggest some alternative?

Thanks for your response Nails! I tried your suggestion but i got the same error message. :(


Report •

July 15, 2010 at 14:08:06
Obviously, you are using a super old version of bash. It apparently does not support shell arithmetic.

Consider using one of the external utilities - such as awk - to perform the arithmetic, but with a system as old as yours, I don't guarantee anything:

factorial=$( echo ""|awk ' { print "'"$factorial"'" * "'"$number"'" } ' )

Report •

Related Solutions

July 16, 2010 at 04:17:29
Thanks for pointing to awk! It was really helpful.


Report •

Ask Question