Thursday 31 October 2013

Howto: Calculate exponent or power in Bash

I have been looking on how to calculate exponent or power in Bash, but most website or blog will show the calculation by using bc (a command line calculator)

I prefer not to use bc in my script, as it is a dependency to another application.

Luckily, I found this blog after searching the Internet for few hours. http://blog.sanctum.geek.nz/calculating-with-bash/

In essence, if you want to calculate exponent or power in Bash, just use this notation:

**

Example:
Gigabyte is 1024^3. In bash notation:

gigabytes=$((bytes / (1024**3)))

[user@server]$
echo $((10737418240/(1024**3)))
10


Bear in mind that bash calculation only return round number.

Happy scripting :)

No comments:

Post a Comment

Please write your comment about this blog post. Thanks! :)