BASH: Factorial using FOR loop not working

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


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

The code is mentioned below:
------------------------------------------------------------------
/home/gc> cat fact.sh
#!/bin/bash
# using one command line parameter

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

Can anyone please help?


Regards,
GC


See More: BASH: Factorial using FOR loop not working

Report •

#1
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 •

#2
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. :(


Regards,
GC


Report •

#3
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

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


Regards,
GC


Report •

Ask Question