POSIX standardizes $(( ... ))
as arithmetic syntax, as can be seen in section 2.6.4 of https://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
However, dash does not support if (( ... ))
to test whether an arithmetic expression has a nonzero output.
How can this be done to be portable to all POSIX-compliant shells?
答案 0 :(得分:1)
Since $(( ... ))
is POSIX-compliant, and test
is POSIX-compliant, you can make $(( ... ))
emit a result which you can then evaluate with test
or its synonym [
.
Because booleans in an arithmetic expression emit 1
for true or 0
for false, you can test directly against their result.
For example:
someVar=13
maxLimit=10
if [ "$(( someVar > maxLimit ))" -gt 0 ]; then
echo "ERROR: someVar value of $someVar is greater than maximum of $maxLimit" >&2
exit 1
fi