Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate modulo in sh script

Tags:

sh

modulo

People also ask

How do you run a modulo in shell script?

To use modulo in the shell, we have to utilize the “expr” command to evaluate its value. So, we have consecutively added three “expr” commands to find out the modulo of two integer values each time by using the “%” operator between them and got three remainder values.

Can you use modulus in JavaScript?

In JavaScript, the modulo operation (which doesn't have a dedicated operator) is used to normalize the second operand of bitwise shift operators ( << , >> , etc.), making the offset always a positive value.

What is $@ in SH?

$@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


If your sh really is sh and not just bash being run as sh then this will work just fine

if [ `expr $n % 5` -eq 0 ]
then
    # do something
fi

If your sh is really bash then put your test in (( )) like so

if (( $n % 5 == 0 ))
then
     # do something
fi

You should use bc when doing math in shell

if [ `echo "3 % 2" | bc` -eq 0 ]

Notes on the above answers

  • Backticks are considered deprecated by now (many further notes), so I advise on switching to $(( ... )) or $( ... ) constructs.

  • Both expr (man page), and bc (man page) are external commands, and as such would cause some measurable slowdown in more complex examples than mine or those above. Furthermore, there already is a way to easily avoid them (both). Also, they might not be available on all systems by default for instance.


Suggested new solution

(Might be imperfect under certain conditions, I did test just basic scenarios.)

The simplest possible while portable and POSIX-ly correct code (no Bashisms (Greg's Wiki on how to re-write Bash snippets to POSIX); (Wikipedia overview on POSIX)) to test oddity (as an example) of a number would be as follows:

#!/bin/sh
n=10
if [ $(( n % 2 )) -eq 0 ]; then
    printf '%s\n' "Number $n is Even"
else
    printf '%s\n' "Number $n is Odd"
fi

You can, of course, test any modulo there, not just if a number is even / odd.