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

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

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
share|improve this answer
    
{ … } 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. –  Gilles 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
add comment
V=`expr "$var" / "$var2" 2>/dev/null`

but if division fails, result is empty.

share|improve this answer
    
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
add comment

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.