I'd like to be able to redirect the stderr of a double-parentheses construct. For example:


would output some error messages if $var2 = 0, I do not want the user to see this.

I know I could simply check for zero before doing the division, but I'd like to know if there is a way to do this redirection, for curiosity and because it might turn out useful in other situations.

I've already tried:

a=$(($var/$var2)) 2> /dev/null

Which does not work and

a=$(($var/$var2 2> /dev/null ))

Which gives a syntax error.


This behaviour is caused by the fact that the calculation is done by the shell itself, not by an external command. To redirect the STDERR of the shell, you have to start it with that redirection, but then you lose all your errors. bash 2> /dev/null

Or you use a brace group, which I think is a more appropriate solution:

{ a=$(( val1 / val2 } )); } 2> /dev/null
  • { … } is not a subshell, which would be written (…); a subshell would not work here since the assignment to a would be local to the subshell. Oct 14 '12 at 19:17
  • Thnx Gillis for correcting a few typos.
    – jippie
    Oct 14 '12 at 19:25
  • 1
    I did not know this thing of "brace group"s. Is there any documentation about them?
    – Bakuriu
    Oct 14 '12 at 19:33
  • pubs.opengroup.org/onlinepubs/9699919799/utilities/…, look for "compound commands", @Bakuriu.
    – Mat
    Oct 15 '12 at 4:59
V=`expr "$var" / "$var2" 2>/dev/null`

but if division fails, result is empty.

  • Tried it, but I cannot reproduce a working result. Can you recheck for accidental typos?
    – jippie
    Oct 14 '12 at 19:47
  • I think he forgot the backticks. Anyway this works too with the backticks(at least for what I've tested). Is there any difference between this solution and jippie's?
    – Bakuriu
    Oct 14 '12 at 20:03
  • @Bakuriu, this solution starts an extra process, whereas jippie's doesn't (not even a subshell). Also, the expr utility and the $((...)) construct accept somewhat different ranges of operations. They handle basic arithmetic the same. Try man expr, and man bash and search for "ARITHMETIC EVALUATION"
    – dubiousjim
    Oct 15 '12 at 4:06

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.