32

I am working on an sh script in which I am in a WHILE loop where a variable gets incremented every iteration, and I'd like to save a file every five iterations.

What I'd normally do (say in C) would be to do an if ( n % 5 == 0) test, but I don't know whether that's possible here..? If it isn't, does anyone have any ideas that would get the job done?

Cheers!

3 Answers 3

66

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
Sign up to request clarification or add additional context in comments.

2 Comments

Note that modulo operation with negative numbers in bash returns only remainder, not mathematical modulo result. This means, that while mathematically -12 mod 10 is 8, bash will calculate it as -2. You can test it with simple echo $((-12 % 10)) (-2) and compare it with python3 python3 -c "print(-12 % 10)" (8).
Second syntax much better, backticks are highly deprecated. Or $(xxxxx).
23

You should use bc when doing math in shell

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

2 Comments

Android Terminal has no bc
This is far obsolete; POSIX sh includes arithmetic expansion since way back.
16

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.