Bash Expr

In Bash, the expr command is used to evaluate arithmetic expressions and perform string operations. It is another way to handle arithmetic calculations and string manipulations within scripts. Here’s an overview of the expr command and its usage:

The basic syntax of the expr command for arithmetic expressions is as follows:

expr <expression>

The <expression> represents the arithmetic expression to be evaluated. The expr command evaluates the expression and prints the result to the standard output.

Here’s an example that demonstrates the usage of the expr command for arithmetic calculations:

#!/bin/bash

result=$(expr 2 + 3)
echo "Result: $result"

a=5
b=2
c=$(expr $a \* $b)
echo "c: $c"

In this example, the expr command is used to evaluate arithmetic expressions and store the results in variables. The first expr command calculates the sum of 2 and 3 and stores it in the result variable. The second expr command multiplies the values of a and b and stores the result in the c variable.

When you run this script, it will output:

Result: 5
c: 10

Apart from arithmetic calculations, the expr command can also perform string operations such as pattern matching, length calculation, and substring extraction. Here’s an example that showcases the usage of the expr command for string operations:

#!/bin/bash

string="Hello, World!"
length=$(expr length "$string")
echo "Length: $length"

substring=$(expr substr "$string" 8 5)
echo "Substring: $substring"

In this example, the first expr command calculates the length of the string and stores it in the length variable. The second expr command extracts a substring starting from position 8 and of length 5 from the original string, storing it in the substring variable.

When you run this script, it will output:

Length: 13
Substring: World

The expr command provides a way to evaluate arithmetic expressions and perform string operations within Bash scripts. It can be useful for simple calculations and manipulations, especially when used in conjunction with variables and command substitution.

Leave a Comment

Your email address will not be published. Required fields are marked *