The Computer Oracle

Can I do basic maths in Bash?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle4

--

Chapters
00:00 Can I Do Basic Maths In Bash?
00:19 Answer 1 Score 13
00:38 Accepted Answer Score 29
00:54 Answer 3 Score 78
01:17 Answer 4 Score 10
01:43 Thank you

--

Full question
https://superuser.com/questions/256023/c...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#bash #ssh

#avk47



ANSWER 1

Score 78


If we are really talking about Bash, not Bourne Shell (sh) or other shells, it's easy.

Bash can compute basic expressions with $((expression)) and here's an example on how you might like to use it:

 a=3
 b=4
 c=$((7*a+b))
 echo $c

or for interactive use, just

 echo $((7*3+4))



ACCEPTED ANSWER

Score 29


Just type bc into the terminal. Then type all the math stuff in after that.

bc stands for "basic calculator"

Then type quit and enter to exit.




ANSWER 3

Score 13


There are a number of command-line utilities for doing simple calculations:

$ expr 100 \* 4
400

$ echo '100 * 4' | bc
400

to name just two of them. Be careful doing multiplication as if you don't escape your * the shell may try and interpret it as a wildcard.




ANSWER 4

Score 10


Well your question is answered, but consider this:

Most of the linux distros have python preinstalled, so why not use it?

Just type

python

in the terminal and then do all the arithmetic you want, like

2+2

Will output 4 :)

You can also do this directly from terminal with the -c python argument.

python -c 'print 2+2'