# bash's arcana with loop



## setevoy (Jun 18, 2014)

Hi.

Have some function with loop:


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

It calls from another script manager.sh by:


```
...
    -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:


```
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:


```
(( i++ )) || echo ++I-ER &>/dev/null
```
 and it's works... But it very strange  :q


----------



## setevoy (Jun 18, 2014)

*Re: bahs's arcana with loop*

Sorry - found problem...


```
set -o errexit
```

But - why 
	
	



```
(( i++ ))
```
 in first iteration returns error?


----------



## RichardM (Jun 18, 2014)

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:


```
i=0
(( i )) && echo true
i=-1
(( i )) && echo true
i=1
(( i )) && echo true
```

only prints "true" on the last two commands.


----------

