bash's arcana with loop

Hi.

Have some function with loop:

Code:
runcfg () {
o=0
while (( o<3 )); do
  echo $o
  (( o++ ))
done
}

It calls from another script manager.sh by:

Code:
...
    -C|--runconfig)
source $APP_BASEDIR/app-install/bin/config_functions; runcfg;
shift;;
...

Let's run it:

$ bash -x manager.sh -run

And look at output:

...
+ runcfg
+ o=0
+ (( o<3 ))
+ echo 0
0
+ (( o++ ))


That's all lines... Nothing else happens.

But! If make little chage and add && after arithmetic call:

Code:
runcfg () {
o=0
while (( o<3 )); do
  echo $o
  (( o++ )) && echo ++OK || echo ++ER
done
}

It works!
...
+ runcfg
+ o=0
+ (( o<3 ))
+ echo 0
0
+ (( o++ ))
+ echo ++ER
++ER
+ (( o<3 ))
+ echo 1
1
+ (( o++ ))
+ echo ++OK
++OK
+ (( o<3 ))
+ echo 2
2
+ (( o++ ))
+ echo ++OK
++OK
+ (( o<3 ))
+ shift
...


What is this?

P.S. Currently I set:

Code:
  (( i++ )) || echo ++I-ER &>/dev/null
and it's works... But it very strange :q
 
Re: bahs's arcana with loop

Sorry - found problem...

Code:
set -o errexit

But - why
Code:
(( i++ ))
in first iteration returns error?
 
It's because the return code of the (( .. )) command is zero (ie true in bash terms) if the value of the expression is non-zero, and non-zero (ie false) if the value of the expression is zero. I've found this behaviour confusing, it's tripped me up before! The expression i++ is zero first time, as you used the post-increment operator. If you changed it to ++i the problem should disappear. So in bash, the following code:

Code:
i=0
(( i )) && echo true
i=-1
(( i )) && echo true
i=1
(( i )) && echo true

only prints "true" on the last two commands.
 
Back
Top