Jamie Lindsey
Jamie Lindsey

Reputation: 993

Doing math in a bash script

The following is a snippet from a script that Generates random passwords with a length of the users choice. I have got the script functioning perfectly as a GUI.

I would like to add some extra functionality, at the bottom of the script is some info for the user

The passwords generated by this application are very strong, here is an example of the strength you can achieve by using this application;

Length of Password:
$newnumber

Character Combinations:
${#matrix}

Calculations Per Second: 
4 billion

Possible Combinations:   2 vigintillion

Based on an average Desktop PC making about 4 Billion calculations per second it would take about 21 quattuordecillion years to crack your password.

As a number that's 21,454,815,022,336,020,000,000,000,000,000,000,000,000,000,000 years!"

How would I get bash to calculate the answer of

`21 quattuordecillion years` 

from

Length of Password:
$newnumber

Character Combinations:
${#matrix}

Calculations Per Second: 
4 billion

Possible Combinations:   2 vigintillion

Upvotes: 0

Views: 310

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84551

Another easy way that provides an intuitive and flexible approach to math in bash is the package [calc]. I have worked with and contributed to calc for a number of years. It is a fully capable (scientific) command line floating point math application. Use in bash is as simple as:

ans=$( calc -p "sqrt($a^2 + $b^2 + $c^2)" )

It is definitely worth a look if you find bc a bit awkward to use.

Upvotes: 0

flexus
flexus

Reputation: 465

An easy way to do math from bash is to use the bc commandline calculator. Here is how you can call it from a bash script:

answer=$(bc << LIMIT_STRING
your math operations here
LIMIT_STRING
)

Upvotes: 1

Related Questions