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
---------- Post updated at 09:33 PM ---------- Previous update was at 06:32 PM ----------
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?
Regards,
GC
You were really close. For arithmetic, use parentheses, not brackets:
(12:40:19\[D@DeCoBox15)
[~]$ cat fact
#!/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
(12:40:21\[D@DeCoBox15)
[~]$ bash fact 12
The factorial of 12 is 479001600
seq is not a bash feature, but an external command. Apparently, your system does not have it. Perhaps you can try jot. Alternatively, you can use a while loop:
f=1 i=1
while [ $i -le $1 ]; do
f=$((f*i))
i=$((i+1))
done
echo $f
Regards,
Alister
Thanks DeCoTwc & alister for your inputs!
@DeCoTwc: I tried your method but those braces also did not work. I got a similar error message.
/home/gc> bash unix1_fact.sh 5
unix1_fact.sh: syntax error near unexpected token `(('
unix1_fact.sh: unix1_fact.sh: line 5: `for (( number = 1; number <= $1 ; number++ ))'
Looks like the bash I am trying on is too old to understand even your suggested syntax.
I tried the same code on newer bash and it worked fine. Anyways, thanks for your input.
@alister: Your method was working fine. Thank You!
I also tried awk; it also works fine on my old bash version.
Regards,
GC