- This Galaxy Watch is one of my top smartwatches for 2024 and it's received a huge discount
- One of my favorite Android smartwatches isn't from Google or OnePlus (and it's on sale)
- The Urgent Need for Data Minimization Standards
- If ChatGPT produces AI-generated code for your app, who does it really belong to?
- The best iPhone power banks of 2024: Expert tested and reviewed
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.