Use Bash to do Math

Math is easy in bash

You don’t need calculators or other apps like “expr”, or languages or compilers to calculate. You can get a lot done in bash (GNU Bourne-Again SHell), and it’s really easy!

$ echo $((10 - 3))
7

Useful operators

x++   variable post-increment
x--   variable post-decrement
++y   variable pre-increment
--y   variable post-decrement
-   unary minus
+   unary plus
!   logical negation
~   bitwise negation
**   exponentiation
*   multiplication
/   division
%   remainder
+   addition
-   subtraction
&&   logical AND
||   logical OR
&   bitwise AND
|   bitwise OR
^   bitwise exclusive OR
<>   left and right bitwise shifts
= !=   equality and inequality

Example

Here’s a simple example of where simple math is useful and easy in Bash. If you need to do some stuff that takes awhile, and you’d like to keep track of how long it takes to “do stuff” in your script, mark the time when you start, and again when you stop. The difference between the two is your elapsed time.

#!/bin/bash
start=$(date +%s)

echo "sleeping for 5 seconds..."
sleep 5

finish=$(date +%s)
echo "$(($finish - $start)) seconds have passed."
exit 0
Posted by admica   @   7 January 2011

Related Posts

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

*

Previous Post
«
Next Post
»
Powered by Wordpress   |   Lunated designed by ZenVerse

Valid XHTML 1.0 Transitional