- Upgrade to Microsoft Office Pro and Windows 11 Pro with this bundle for 87% off
- Get 3 months of Xbox Game Pass Ultimate for 28% off
- Buy a Microsoft Project Pro or Microsoft Visio Pro license for just $18 with this deal
- How I optimized the cheapest 98-inch TV available to look and sound incredible (and it's $1,000 off)
- The best blood pressure watches of 2024
Doing math on the Linux command line
You can also assign values to variables and use those variable names in your calculations as shown in the examples below.
$ num1=11 $ num2=17 $ expr $num1 + $num2 28
The expr command can also work to some extent with strings. The expressions below reports the length of the string provided, but not counting the quotes.
$ expr length "hello" 5 $ expr length "Don't spend a day without having a little fun!" 46
Comparing strings with expr
The expr command also provides a way to compare strings, but note how the longer string must be provided first.
$ expr Linux : Linux 5 $ expr LinuxNow : Linux 5 $ expr Linux : LinuxNow 0
Getting help
You can get some help on using the expr command by using the –help option (expr –help). The bulk of this will explain how the various expressions work. It includes explanations such as these:
Print the value of EXPRESSION to standard output. A blank line below separates increasing precedence groups. EXPRESSION may be: ARG1 | ARG2 ARG1 if it is neither null nor 0, otherwise ARG2 ARG1 & ARG2 ARG1 if neither argument is null or 0, otherwise 0 ARG1 < ARG2 ARG1 is less than ARG2 ARG1 <= ARG2 ARG1 is less than or equal to ARG2 ARG1 = ARG2 ARG1 is equal to ARG2 ARG1 != ARG2 ARG1 is unequal to ARG2 ARG1 >= ARG2 ARG1 is greater than or equal to ARG2 ARG1 > ARG2 ARG1 is greater than ARG2 ARG1 + ARG2 arithmetic sum of ARG1 and ARG2 ARG1 - ARG2 arithmetic difference of ARG1 and ARG2 ARG1 * ARG2 arithmetic product of ARG1 and ARG2 ARG1 / ARG2 arithmetic quotient of ARG1 divided by ARG2 ARG1 % ARG2 arithmetic remainder of ARG1 divided by ARG2 STRING : REGEXP anchored pattern match of REGEXP in STRING
The commands below are examples of expr commands.
$ expr 60 / 30 * 100 200 $ expr 20 / 30 * 100 0
Oops! What happened in the second example above? The expr command is not going to hold onto numbers less than 0. So, you need to use some other command.