Get ceiling integer from number in linux (BASH)

Mint picture Mint · Mar 7, 2010 · Viewed 54.4k times · Source

How would I do something like:

ceiling(N/500)

N representing a number.

But in a linux Bash script

Answer

Kalle picture Kalle · Sep 21, 2012

Why use external script languages? You get floor by default. To get ceil, do

$ divide=8; by=3; (( result=(divide+by-1)/by )); echo $result
3
$ divide=9; by=3; (( result=(divide+by-1)/by )); echo $result
3
$ divide=10; by=3; (( result=(divide+by-1)/by )); echo $result
4
$ divide=11; by=3; (( result=(divide+by-1)/by )); echo $result
4
$ divide=12; by=3; (( result=(divide+by-1)/by )); echo $result
4
$ divide=13; by=3; (( result=(divide+by-1)/by )); echo $result
5
....

To take negative numbers into account you can beef it up a bit. Probably cleaner ways out there but for starters

$ divide=-10; by=10; neg=; if [ $divide -lt 0 ]; then (( divide=-divide )); neg=1; fi; (( result=(divide+by-1)/by )); if [ $neg ]; then (( result=-result )); fi; echo $result
-1

$ divide=10; by=10; neg=; if [ $divide -lt 0 ]; then (( divide=-divide )); neg=1; fi; (( result=(divide+by-1)/by )); if [ $neg ]; then (( result=-result )); fi; echo $result
1

(Edited to switch let ... to (( ... )).)