Hi, this is Sandra Henry-Stocker, author of the “Unix as a Second Language” blog on NetworkWorld.
In this Linux tip, we’re going to look at an easy way to do math on the command line using double parentheses. This construct is often used in scripts, but also works just fine on the command line.
To simply add two numbers together, you could do this:
Notice the syntax – a $, two open parens, a + sign and two closing parens. If you want to save the result in a variable, do this:
You can also add two variables together. Notice we don’t put $ in front of the variable names inside the parens:
And please understand, it’s not just addition. Using double parentheses, you can add, subtract, multiple, divide, increment, decrement and even get the square, cube and so on of a number. Here are some examples:
As I hope I’ve shown, you can work with variables or just use numbers depending on what it is you’re trying to do.
That’s your Linux tip for doing math with double parentheses. If you have questions or would like to suggest a topic, please add a comment below. And don’t forget to subscribe to the IDG Tech(talk) channel on YouTube.
If you liked this video, please hit the like and share buttons. For more Linux tips, be sure to follow us on Facebook, YouTube and NetworkWorld.com.