What is a POSIX-compliant alternative to if (( ... ))?

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?

Upvotes: 2

Views: 396

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295679

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

Upvotes: 1

Related Questions