Step-by-Step Tutorial: Assessing Arithmetic Expressions with Linux Command 'Expr'

Step-by-Step Tutorial: Assessing Arithmetic Expressions with Linux Command 'Expr'

Christopher Lv13

Step-by-Step Tutorial: Assessing Arithmetic Expressions with Linux Command ‘Expr’

Key Takeaways

  • The expr command can evaluate expressions and output the corresponding value. You can use it to perform arithmetic calculations, comparisons, and string operations.
  • Using the expr command, you can search for specific patterns in text, validate user input, and even replace text based on defined patterns.
  • The expr command can also manipulate strings using string functions like finding length, comparing strings, and extracting substrings.

Want to do some simple calculations in Linux? Just use the expr command. This command can perform various operations, such as evaluating expressions, extracting substrings, comparing strings, and more. Using expr, you can add, subtract, multiply, or divide two numbers, and get the answer as the output.

## The expr Command

expr is a tool that can perform calculations and manipulate strings based on the expressions you provide. With the expr command, you can perform various operations on integers and strings, like comparing values or finding specific patterns using regular expressions .

You can pass multiple expressions to expr as arguments, separated by spaces. It not only evaluates an expression but also shows its corresponding output on the terminal. The expr command works both in the Bash terminal and shell scripts .

The expr command is handy when manipulating data or doing calculations without leaving the terminal. However, you need to be careful with the syntax and the order of the expressions, or else the command will fail and display an error message.

The syntax of the expr command is:

    `expr expression`

… where the expression can be a combination of arguments and operators. For example, the below-given expression evaluates the operation between arg1 and arg2 and displays the result:

    `expr arg1 operator arg2`

The arguments can be numbers or strings, depending on the operator. The operators can be arithmetic, relational, string-related, or logical. It is the symbol that specifies the operation to be performed. For example, for integers, you can use operators like +, -, *, /, and %.

For strings, you can use regular expressions and character sets to find matches and indexes. You can also use parentheses to group expressions and backslashes to escape special characters.

expr Command Options

While expr doesn’t have traditional command-line options, it offers versatile operators for arithmetic, string manipulation, and comparison. Furthermore, you can use the --help option to show expr’s help page, which explains its syntax, features, and examples:

    `expr --help`

Linux terminal with expr command documentation

FX PRO (Gold Robot + Silver Robot(Basic Package))

To check the expr command version, run:

    `expr --version`

Linux terminal that shows the version number and developer details of the expr command

This option displays the version number, source code, license, and author of expr.

Performing Arithmetic Operations With expr

To use the expr command for basic arithmetic operations, write the command expr followed by a space. Then, write the expression that you want to evaluate. This expression is a combination of integers and operators such as +, -, *, and /. Make sure to separate each token (integer or operator) in the expression by a space character.

For example, if you want to find out the sum of 15 and 12 using expr, you can write:

    `expr 15 + 12`

Linux terminal showing the addition of two variables using expr command

Similarly, you can use the expr command to perform other arithmetic operations, such as subtraction, multiplication, and division. Let’s evaluate some expressions using the expr command:

    `expr 15 - 12  

expr 15 * 5
expr 10 / 2`

Linux terminal showing various arithmetic operations with expr command

You need to escape the multiplication (*) operator with a backslash (\) to avoid shell expansion. Otherwise, the shell will try to match the operator (*) with the filenames in the current directory and pass them to the expr command, which will cause an error.

Linux terminal with syntax error

You can also prevent the shell from interpreting the characters by quoting the arguments and operators properly:

    `expr "5" "*" "3"`

Linux terminal with variables and operator quotes with double quotations marks

Comparing Two Expressions With expr

To compare two expressions using the expr command, you can use logical operators such as =, <, >, and !=. If you see the command output one, the condition is true, otherwise, it is false, and the value returned is zero.

For example, to check if the first argument is equal to the second argument, we use the = operator:

    `expr 40 = 50`

Linux terminal displaying checking of the two numbers equality using expr command

Now, let’s check whether the first argument is smaller than the other argument. For that, we use the < operator:

    `expr 40 \< 50`

Linux terminal showing commands to check the smaller variable using the expr command with less than operator

You can also check whether the values are not equal. To do that, simply use the != operator between the two arguments’ values:

    `expr 45 \!= 55`

Linux terminal showing the comparison of two values using the expr command with not equal to operator

Here, the output 1 indicates that 45 is not equal to 55.

This way, the expr command provides a simple and effective method to compare numerical values.

Like the multiplication (*) operator, the <, >, and != operators also need to be escaped with a backslash (\). Otherwise, they may be interpreted as special characters by the shell.

Finding a String’s Length With expr

To find the length of a string using the expr command, you can use the length method. This operator will return the number of characters present in the given string to the output.

For example, to find the length of the string ‘How To Geek’, run this command:

    `expr length 'How To Geek'`

Linux terminal showing the length using the expr command with the length operator

The output is 11 because there are nine characters and two white spaces in the string. If you want to find the length of a string without whitespace, you can use other commands like tr or awk to remove them first. For example:

    `expr length "$(echo 'How To Geek' | tr -d ' ')"`

Linux terminal displaying the string length without the including the white spaces

The output will be nine because the tr command deletes all the spaces in the string before passing it to the expr length command.

Matching Two Strings With expr

One of the operations that expr offers is the comparison of two strings. 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.

The syntax for using this operator is:

    `expr string1 : string2`

This compares the two strings and returns the number of matching characters from the beginning of the string.

For example, the below command will output five, as both strings have the first five characters in common :

    `expr 'HowToGeek' : 'HowTo'`

Linux terminal showing the matching of two different strings using the expr command

Consider another example, where two given strings are the same:

    `expr 'How To Geek' : 'How To Geek'`

Linux terminal showing the matching of two same strings using the expr command

The output is 11 as both strings have all the characters in common, including the white spaces.

If there is no matching character present, then the output will be zero:

    `expr 'How To Geek' : 'Linux'`

The Linux terminal displays how to match different string variables using the expr command

Incrementing and Decrementing a Variable With expr

The expr command can also evaluate an expression that increments and decrements a variable’s value. Further, you can assign the result to a new variable.

Consider the example below, where we have defined a variable “a” and incremented its value using the expr command:

    `` a=20  

a=expr $a + 1
echo $a ``

The Linux terminal displays usage of expr command to increment the variable value by 1

Similarly, to decrement the variable value, use the same syntax but replace the addition sign with subtraction:

    `` a=20  

a=expr $a - 1
echo $a ``

The Linux terminal displays usage of expr command to decrement the variable value by 1

## Extracting a Substring Using expr

To extract a substring from a given string, you can use the expr command with a substr operator. This way, you can extract specific information from a larger text, such as name, date, or any code. You can also use this operator to remove unwanted characters or spaces from a string.

Consider the following example commands, where a new string is initialized. After that, using the expr command, we will get the second to fifth characters from the string “HowToGeek”:

    `` a=HowToGeek  

b=expr substr $a 2 5
echo $b ``

The Linux terminal displays the usage of the expr command with substr option to extract a substring

WinUtilities Pro

Performing expr Operations Using a Shell Script

To automate expression handling using the expr command, you can create a custom shell script. Shell scripts are multipurpose tools that can help you do more with less. With shell scripts, you can automate repetitive tasks, manipulate data, and perform complex calculations.

For example, you can create a script for adding two numbers using the expr command. First, you need to create a file with a “.sh” extension, such as “my_script.sh”. This tells the shell that it is a script file. Next, you need to write a code that can take two numbers as input and output their sum. Here is a sample script that can do that:

    `` echo "Enter two numbers"   

read a
read b
sum=expr $a + $b
echo “Sum of two numbers is= $sum” ``

Bash script file containing the script of adding two numbers

This script uses the expr command to evaluate arithmetic operations on the variables “a” and “b.” The echo command prints a message to the standard output, while the read command reads a line from the standard input and puts it in a variable.

Next, to make this script executable, run the chmod command:

    `chmod +x my_script.sh`

Now, proceed with the execution of the script by running:

    `./my_script.sh`

Linux terminal displaying the execution of bash script file and displays the output

You will be prompted to enter two numbers. After entering the numbers, you will see the script will display the sum of both numbers on screen. You can also modify the script to perform other operations or tasks as per your needs.

Greeting Card Builder

Try Some Alternative Linux Commands

This article mainly focuses on the expr command, but you can also try a few other commands for various operations. 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.

  • Title: Step-by-Step Tutorial: Assessing Arithmetic Expressions with Linux Command 'Expr'
  • Author: Christopher
  • Created at : 2024-08-30 21:20:39
  • Updated at : 2024-08-31 21:20:39
  • Link: https://some-approaches.techidaily.com/step-by-step-tutorial-assessing-arithmetic-expressions-with-linux-command-expr/
  • License: This work is licensed under CC BY-NC-SA 4.0.