Bash – Redirect stderr of the double-parentheses construct

arithmeticbashio-redirectionstderr

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

a=$(($var/$var2))

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.

Best Answer

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
Related Question