2

I'm having a weird issue incrementing a bash variable that seems to be breaking after my first attempt at incremntation that I cannot pin down, here is a sample of what I am doing and the debug output, anyone see any reason this should NOT work?

I am currently on GNU bash, version 4.2.45(1)-release (i686-pc-linux-gnu)

#!/bin/bash
set -ex 
declare -i elem=0
echo $elem # 0
    (( elem++ )) # breaks
echo $elem # 1 but never encountered
while IFS=$'\n' read -r line || [[ -n "$line" ]]; do
    (( elem++ ))
    echo $elem
done <"${1}" # foo\nbar\nbaz

Output

./incr.sh test
+ declare -i elem=0
+ echo 0
0
+ ((  elem++  ))

The weirdest part is by changing the initial incrementor to (( elem+=1 )) the entire program increments correctly, this seems extremely buggy to the eye...

#!/bin/bash
set -ex 
declare -i elem=0
echo $elem
    (( elem+=1 ))
echo $elem
while IFS=$'\n' read -r line || [[ -n "$line" ]]; do
    (( elem++ ))
    echo $elem
done <"${1}" # foo\nbar\nbaz

Output

+ declare -i elem=0
+ echo 0
0
+ ((  elem+=1  ))
+ echo 1
1
+ IFS='
'
+ read -r line
+ ((  elem++  ))
+ echo 2
2
+ IFS='
'
+ read -r line
+ ((  elem++  ))
+ echo 3
3
+ IFS='
'
+ read -r line
+ ((  elem++  ))
+ echo 4
4
+ IFS='
'
+ read -r line
+ [[ -n '' ]]
4
  • Where is filename=test coming from? I don't see that in the script. Commented Nov 20, 2013 at 18:57
  • Sorry I changed the code to just use $1 as the input file, if you look again I changed the input, sry I was using a older versions output Commented Nov 20, 2013 at 18:58
  • I can't reproduce it: ideone.com/jm3CQR Commented Nov 20, 2013 at 19:11
  • Why did you delete your code? The question is nonsensical without the code. Commented Dec 30, 2013 at 19:23

1 Answer 1

3

set -e makes your script exit when any command returns failure.

(( 0 )), and equivalently elem=0; (( elem++ )) returns failure.

Therefore, the script exits.

If you set -e and want to run commands whose status you don't care, about, you can use

(( elem++ )) || true
Sign up to request clarification or add additional context in comments.

5 Comments

Awesome anwer, waiting to accept =) thank you, great catch, didn't see that
Why does ((elem++)) return failure?
because elem evaluates as bool(0) ;)
Another fix would be to use pre-increment (( ++elem )), since this will evaluate to 1?
@Barmar that happens to work in this case, but if elem=-1 you're back to the same problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.