什么是 if (( ... )) 的 POSIX 兼容替代方案?

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

POSIX 将 $(( ... )) 标准化为算术语法,如 https://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html

的第 2.6.4 节所示

但是,dash 不支持if (( ... )) 测试算术表达式是否具有非零输出。

如何才能将其移植到所有 POSIX 兼容的 shell 中?

因为 $(( ... )) 是 POSIX 兼容的,而 test 是 POSIX 兼容的,你可以让 $(( ... )) 发出一个结果,然后你可以用 test 或其同义词 [.

求值

因为算术表达式中的布尔值发出 1 表示真或 0 表示假,您可以直接测试它们的结果。

例如:

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