Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a problem with a linux shell script (sh).

I'm trying to write a script that calculates combinations, but I think I get overflows when trying to calculate faculties. So, I'm trying another technique. In this technique I used this:

a=`expr $var1 \* $var2 / $var3`

This is giving errors, and apperently, I can't do this:

a=`expr ($var1 \* $var2) / $var3`

because this gives errors as well.

How do I do it?

share|improve this question
    
What errors are you getting? That works in bash at least –  Michael Mrozek Oct 30 '10 at 20:20
    
expr: syntax error –  3sdmx Oct 30 '10 at 20:21

2 Answers 2

You can use dc for arbitrary precision results:

precision=4 var1=3 var2=4 var3=5
a=`echo "$precision k $var1 $var2 * $var3 /p" | dc`

should work in about every Unix variant since 1977 or so. If you know you have gnu dc available the more concise

a=`dc -e "$precision k $var1 $var2 * $var3 /p"`

can be used.

share|improve this answer

For your example with parens, you must escape them too: expr \( $var1 + $var2 \) / $var3 (and don't omit the spaces, or expr will complain).

In bash you can also use built-in arithmetic expansion like this: echo $(( ($var1+$var2)/$var3 ))

And for infix calculations there's bc (while dc is for reverse-polish notation).

share|improve this answer
    
getcombination() { tempres=1 a=expr \( $2 - $1 \) + 1 b=1 while [ a -le $2 -a b -le $1 ] do tempres=expr \( $tempres \* a \) / b a=expr $a + 1 b=expr $b + 1 done echo $tempres } This still gives expr errors.... –  3sdmx Oct 31 '10 at 11:48
    
Could you please use pastebin or similar service to post the exact offending code (preferably, the bare minimum of it needed to reproduce your problem)? I'm having hard time de-crypting what you put in this comment. –  alex Nov 1 '10 at 10:10
4  
@3sdmx: just don't bother with expr, use the shell arithmetic $((…)) instead. @alex: $((…)) isn't specific to bash, it's in POSIX. –  Gilles Nov 1 '10 at 18:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.