- Join BJ's Wholesale Club for $20, and get a $20 gift card: Deal
- Delivering better business outcomes for CIOs
- Docker Desktop 4.35: Organization Access Tokens, Docker Home, Volumes Export, and Terminal in Docker Desktop | Docker
- Cybercriminals Exploit DocuSign APIs to Send Fake Invoices
- Your iPhone's next iOS 18.2 update may come earlier than usual - with these AI features
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.