Addition in bash

David N. Lombard dnl at speakeasy.net
Wed Oct 14 18:33:36 UTC 2009


Ray Parrish wrote:
> David N. Lombard wrote:

>> Interval=${1:-1}
>>   
> Could you please explain the above line, and the one below for Duration, 
> as I do not see what that code is supposed to be doing.

This uses bash's built-in capability to test for a null value or no 
value and make an alternate assignment.

So, Interval is given the value of $1 if and only if $1 is non-null; if 
$1 is not set or is "blank" is sets Interval to 1.

Thus Duration=${2:-300} sets Duration to the non-null value of $2 
otherwise Duration is 300

>
>>    [[ $Seconds -ge 60 ]] && (( Seconds -= 60 )) && (( Minutes += 1 ))
>>   
> That last line did not work correctly, it decremented Seconds, but 
> neglected to change the value of Minutes... got any idea why??? This 
> error was with Interval set to 1 second, with Interval set to 7 seconds 
> Minutes increments correctly.

Oops, my bad.  Needed to reverse Minutes and Seconds.
When Seconds *was* 60, the new value of 0 caused it failed the &&.

   [[ $Seconds -ge 60 ]] && (( Minutes += 1 )) && (( Seconds -= 60 ))

&& is a short-circuit AND operator, as in C.  The exit code of the 
command/operation before the  && is tested.  If true (exit==0), then the 
command/operation following the && is executed; if not (exit!=0), the 
command/operation following the && is ignored.

|| is a short-circuit OR operator.  If the command/operation before the 
|| is not true (exit!=0), the command/operation following the || is 
executed; if true (exit==0), the command/operation following the || is 
not executed.

These are idiomatic examples used in preference of single-operation if 
statements

   [[ conditional_statement ]] && do_something_if_true

and

   [[ conditional_statement ]] || do_something_if_false

This also works

   [[ conditional_statement ]] && do_if_true || do_if_false

But be careful you understand how that last one works!

-- 
David N. Lombard




More information about the ubuntu-users mailing list