voedger / kb

Knowledge base
0 stars 0 forks source link

bash: why the cycle breaks? #12

Open maxim-ge opened 11 months ago

maxim-ge commented 11 months ago
#!/usr/bin/env bash

set -euo pipefail

hosts=("DBNode1" "DBNode2" "DBNode3")
i=0
for host in "${hosts[@]}"; do
  echo $host
  echo $i
  ((i++))
done

Result:

DBNode1
0
maxim-ge commented 11 months ago
Hint

Works (`((++i))`): ```bash set -euo pipefail hosts=("DBNode1" "DBNode2" "DBNode3") i=0 for host in "${hosts[@]}"; do echo $host echo $i ((++i)) done ``` Result: ``` DBNode1 0 DBNode2 1 DBNode3 2 ```

maxim-ge commented 11 months ago
Explanation

> GPT4: The ((...)) arithmetic command in Bash has a peculiar behavior. It returns a 0 exit status ("success") if the result of the arithmetic operation is non-zero, and it returns 1 ("error") if the result is zero. In your case, the ((i++)) command actually returns an exit status of 1 because the result of the operation i++ is evaluated as 0 before incrementing i. ```bash #!/usr/bin/env bash ((0)) || echo '((0))': error ((1)) && echo '((1))': ok i=0 ((i++)) || echo '((0++))': error, "i=$i" i=0 ((++i)) && echo '((++0))': ok, "i=$i" i=0 ((i++, i)) && echo '((0++, 0+1))': ok, "i=$i" i=-1 ((i++, 1)) && echo '((0++, 1))': ok, "i=$i" ```