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 the expr command that allows you to do mathematical calculations on the command line. Here are some very simple examples:
We can also multiply numbers, but notice we would need to use a backslash:
For division (the second command shows the remainder), there are no decimal places.
The expr command can also be used for Boolean calculations. This is an AND calculation.
If both numbers aren’t greater than 0, the result is zero.
You can do comparisons (a response of 0 means “not the same”):
And you can test whether one variable is greater or less than another:
1 means the expression is true; 0 means it is not.
You need to be a little careful with more complex commands as in this command where the division is done prior to the addition.
You can use the expr command on the command line or in scripts for comparing variables.
That’s your Linux tip for the expr command. 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.