User Tools

Site Tools


bash:math:error_with_expression

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

bash:math:error_with_expression [2021/01/26 12:02] – created peterbash:math:error_with_expression [2021/01/26 12:04] (current) peter
Line 1: Line 1:
 ====== BASH - Math - Error with ((expression)) ====== ====== BASH - Math - Error with ((expression)) ======
 +
 +<WRAP important>
 +**WARNING:**  Be careful when using **<nowiki>((expression))</nowiki>**.
 +</WRAP>
 +
 +
 +----
 +
 +====== Arithmetic evaluation and errexit trap ======
 +
 +<code bash>
 +count=0
 +things="0 1 0 0 1"
 +
 +for i in $things;
 +do
 +  if [ $i == "1" ]; then
 +    (( count++ ))
 +  fi
 +done
 +
 +echo "Count is ${count}"
 +</code>
 +
 +returns:
 +
 +<code bash>
 +2
 +</code>
 +
 +----
 +
 +===== Check the return code =====
 +
 +<code bash>
 +echo $?
 +</code>
 +
 +returns:
 +
 +<code bash>
 +0
 +</code>
 +
 +<WRAP info>
 +**NOTE:**  A **0** indicates success.
 +
 +A **1** indicates failure.
 +
 +</WRAP>
 +
 +
 +<WRAP box>
 +**NOTE:**  This looks fine; but there is a small gotcha:
 +
 +The **<nowiki>((expression))</nowiki>** is evaluated according to the Arithmetic Evaluation rules.
 +
 +  * If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1.
 +  * This is exactly equivalent to **let "expression"**.
 +
 +But if you run this script with **-e** or enable errexit:
 +
 +<code bash>
 +bash -e test.sh
 +</code>
 +
 +then count++ is going to return 0 (post-increment) and the script will stop.
 +
 +Checking the result:
 +
 +<code bash>
 +echo $?
 +</code>
 +
 +returns:
 +
 +<code bash>
 +1
 +</code>
 +
 +This time a failure.
 +
 +A definite trap to watch out for!  Do not use **<nowiki>((expression))</nowiki>** here.
 +</WRAP>
  
bash/math/error_with_expression.1611662556.txt.gz · Last modified: 2021/01/26 12:02 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki