bash:math:error_with_expression
Differences
This shows you the differences between two versions of the page.
bash:math:error_with_expression [2021/01/26 12:02] – created peter | bash: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: | ||
+ | </ | ||
+ | |||
+ | |||
+ | ---- | ||
+ | |||
+ | ====== Arithmetic evaluation and errexit trap ====== | ||
+ | |||
+ | <code bash> | ||
+ | count=0 | ||
+ | things=" | ||
+ | |||
+ | for i in $things; | ||
+ | do | ||
+ | if [ $i == " | ||
+ | (( count++ )) | ||
+ | fi | ||
+ | done | ||
+ | |||
+ | echo "Count is ${count}" | ||
+ | </ | ||
+ | |||
+ | returns: | ||
+ | |||
+ | <code bash> | ||
+ | 2 | ||
+ | </ | ||
+ | |||
+ | ---- | ||
+ | |||
+ | ===== Check the return code ===== | ||
+ | |||
+ | <code bash> | ||
+ | echo $? | ||
+ | </ | ||
+ | |||
+ | returns: | ||
+ | |||
+ | <code bash> | ||
+ | 0 | ||
+ | </ | ||
+ | |||
+ | <WRAP info> | ||
+ | **NOTE: | ||
+ | |||
+ | A **1** indicates failure. | ||
+ | |||
+ | </ | ||
+ | |||
+ | |||
+ | <WRAP box> | ||
+ | **NOTE: | ||
+ | |||
+ | The **< | ||
+ | |||
+ | * 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 " | ||
+ | |||
+ | But if you run this script with **-e** or enable errexit: | ||
+ | |||
+ | <code bash> | ||
+ | bash -e test.sh | ||
+ | </ | ||
+ | |||
+ | then count++ is going to return 0 (post-increment) and the script will stop. | ||
+ | |||
+ | Checking the result: | ||
+ | |||
+ | <code bash> | ||
+ | echo $? | ||
+ | </ | ||
+ | |||
+ | returns: | ||
+ | |||
+ | <code bash> | ||
+ | 1 | ||
+ | </ | ||
+ | |||
+ | This time a failure. | ||
+ | |||
+ | A definite trap to watch out for! Do not use **< | ||
+ | </ | ||
bash/math/error_with_expression.1611662556.txt.gz · Last modified: 2021/01/26 12:02 by peter