User Tools

Site Tools


bash:arithmetic_evaluation_and_errexit_trap

Differences

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

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
bash:arithmetic_evaluation_and_errexit_trap [2021/01/09 14:39] peterbash:arithmetic_evaluation_and_errexit_trap [2021/01/26 12:00] (current) – removed peter
Line 1: Line 1:
-====== BASH - 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! 
-</WRAP> 
  
bash/arithmetic_evaluation_and_errexit_trap.1610203148.txt.gz · Last modified: 2021/01/09 14:39 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki