问题描述
我想做这样的事情:
if [ $1 % 4 == 0 ]; then
...
但这不起作用.
我需要做什么?
推荐答案
read n
if ! ((n % 4)); then
echo "$n divisible by 4."
fi
(( ))
运算符将表达式计算为 C 算术,并返回布尔值.
The (( ))
operator evaluates expressions as C arithmetic, and has a boolean return.
因此,(( 0 ))
为假,(( 1 ))
为真.[1]
Hence, (( 0 ))
is false, and (( 1 ))
is true. [1]
$(( ))
运算符也扩展了 C 算术表达式,但它不是返回真/假,而是返回值.因此,如果 $(( ))
以这种方式,您可以测试输出: [2]
The $(( ))
operator also expands C arithmetic expressions, but instead of returning true/false, it returns the value instead. Because of this you can test the output if $(( ))
in this fashion: [2]
[[ $(( n % 4 )) == 0 ]]
但这无异于:if (function() == false)
.因此,更简单、更惯用的测试是:
But this is tantamount to: if (function() == false)
. Thus the simpler and more idiomatic test is:
! (( n % 4 ))
[1]:现代 bash 处理的数字最大为您机器的 intmax_t
大小.
[1]: Modern bash handles numbers up to your machine's intmax_t
size.
[2]:请注意,您可以将 $
放在 (( ))
内,因为它会取消引用其中的变量.
[2]: Note that you can drop $
inside of (( ))
, because it dereferences variables within.
这篇关于如果在 bash 中进行语句算术,我该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!