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?

  • 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

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.


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).

  • 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 'SO- stop being evil' Nov 1 '10 at 18:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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