Quick Links
Summary
Want to do some simple calculations in Linux?
Just use the expr command.
you could pass multiple expressions to expr as arguments, separated by spaces.
Hannah Stryker / How-To Geek
It not only evaluates an expression but also shows its corresponding output on the terminal.
The expr command works both in theBash terminalandshell scripts.
The expr command is handy when manipulating data or doing calculations without leaving the terminal.
The operators can be arithmetic, relational, string-related, or logical.
It is the symbol that specifies the operation to be performed.
For strings, you’re free to use regular expressions and character sets to find matches and indexes.
it’s possible for you to also use parentheses to group expressions and backslashes to escape special characters.
Then, write the expression that you want to evaluate.
This expression is a combination of integers and operators such as +, -, *, and /.
check that to separate each token (integer or operator) in the expression by a space character.
This way, the expr command provides a simple and effective method to compare numerical values.
Otherwise, they may be interpreted as special characters by the shell.
This operator will return the number of characters present in the given string to the output.
For this, use the colon (:) operator with the expr command.
This operator returns the number of characters that match at the beginning of both strings.
Further, you could assign the result to a new variable.
you’re able to also use this operator to remove unwanted characters or spaces from a string.
Consider the following example commands, where a new string is initialized.
Shell scripts are multipurpose tools that can help you do more with less.
This tells the shell that it is a script file.
Next, you should probably write a code that can take two numbers as input and output their sum.
After entering the numbers, you will see the script will display the sum of both numbers on screen.
you could also modify the script to perform other operations or tasks as per your needs.
These commands include declare, let, and bc.
All these command-line tools can perform simple to intricate mathematical operations on defined values.
The declare command can create and modify variables and their attributes.
Similarly, the let command evaluates arithmetic expressions on shell variables.
Lastly, bc is a command-line calculator that supports arbitrary precision arithmetic and various math functions.
It can also parse a scripting language that supports loops, conditional statements, and variables.