Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do if statement arithmetic in bash?

Tags:

bash

scripting

I want to do something like this:

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

But this does not work.

What do I need to do instead?

like image 969
jmasterx Avatar asked Nov 28 '11 23:11

jmasterx


People also ask

What is Bash if [- N?

A null string in Bash can be declared by equalizing a variable to “”. Then we have an “if” statement followed by the “-n” flag, which returns true if a string is not null. We have used this flag to test our string “name,” which is null.


2 Answers

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.

like image 70
guns Avatar answered Oct 09 '22 11:10

guns


a=4 if [ $(( $a % 4 )) -eq 0 ]; then                                      echo "I'm here" fi 
like image 26
Jan Vorcak Avatar answered Oct 09 '22 11:10

Jan Vorcak