Addition in bash
Ray Parrish
crp at cmc.net
Thu Oct 15 04:05:52 UTC 2009
David N. Lombard wrote:
> 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
>
Thanks for the leg up on the testing for null, and assigning alternate
values. Pretty handy to have it all in line. I've updated the script to
use your method.
>
>>> [[ $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 ))
>
Thank you, my only guess had been that the -ge operator was somehow
typoed. 8-)
> && 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!
>
Thanks for all the help streamlining my code. I've added a web page to
Ray's Links with the new timer/stop watch script available as open
source software.
Later, Ray Parrish
--
The Future of Technology.
http://www.rayslinks.com/The%20Future%20of%20Technology.html
Ray's Links, a variety of links to usefull things, and articles by Ray.
http://www.rayslinks.com
Writings of "The" Schizophrenic, what it's like to be a schizo, and other
things, including my poetry.
http://www.writingsoftheschizophrenic.com
More information about the ubuntu-users
mailing list