According to the bash
man
page,
while list-1; do list-2; done
The while command continuously executes the list list-2 as long as the last command in the list, list-1, returns an exit status of zero.
I'm trying to make sense of how bash is interpreting the exit codes of arithmetical expressions when they appear at the end of list-1. I started with some experiments:
$ echo $((1))
1
$ ((1)); echo $?
0
$ echo $((! 1))
0
$ ((! 1)); echo $? # Hm, what does this exit code mean?
1
$ while ((1)); do echo "yes"; break; done
yes
# This could be responding to either the exit code of ((1))
# or to it's value, 1 meaning true
$ while ((! 1)); do echo "yes"; break; done
# This could be responding to either the exit code of ((! 1)),
# or to it's value, 0 meaning false
$ while ! ((1)); do echo "yes"; break; done
# this ! should change the exit code, not the value,
# so it appear to be responding to the exit code
$ echo $((0))
0
$ ((0)); echo $? # Hm, what does this exit code mean?
1
$ echo $((! 0)))
1
$ ((! 0)); echo $?
0
$ while ((0)); do echo "yes"; break; done
# This could be responding to either the exit code of ((0))
# or to it's value, 0 meaning false
$ while ((! 0)); do echo "yes"; break; done
yes
# This could be responding to either the exit code of ((! 0))
# or to it's value, 1 meaning true
$ while ! ((0)); do echo "yes"; break; done
yes
# this ! should change the exit code, not the value,
# so it appears to be responding to the exit code.
So, after fixing two errors (thanks @Barmar), there is a consistent interpretation based on the while loop looking at exit codes. What remains obscure is why the exit code of ((0))
is failure, and the exit code of ((1))
is success.
I came across this while trying to capture exit codes of functions in the while condition for use when the loop breaks:
while <function>; do
<stuff>
done
# I need the exit code of <function> here.
So, perhaps this way:
while <function>; ((! (RESULT=$?) )); do # alternative ! (( RESULT=$? ))
<stuff>
done