Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

scripting - How do I do if statement arithmetic in bash?

I want to do something like this:

if [ $1 % 4 == 0 ]; then
...

But this does not work.

What do I need to do instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
read n
if ! ((n % 4)); then
    echo "$n divisible by 4."
fi

The (( )) operator evaluates expressions as C arithmetic, and has a boolean return.

Hence, (( 0 )) is false, and (( 1 )) is true. [1]

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 ]]

But this is tantamount to: if (function() == false). Thus the simpler and more idiomatic test is:

! (( n % 4 ))

[1]: Modern bash handles numbers up to your machine's intmax_t size.

[2]: Note that you can drop $ inside of (( )), because it dereferences variables within.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...