Examples of the expr Command in Shell

Overview of expr

The expr command is used for integer arithmetic and string operations (like length and pattern matching) in shell scripts.

1. Syntax and Basic Usage

Only integer arithmetic is supported. Operators and numbers must be separated by spaces; otherwise, errors occur. The multiplication operator (*) must be escaped. When using expr in shell variable assignments, enclose the expression in backticks.

expr 2 + 2
expr 2 - 2
expr 2 \* 2
expr 2 / 2
i=5
i=`expr $1 + 6`
echo $i

Notes:

  • Every operator and operand must have atleast one space around them.
  • The multiplication operator must be escaped with a backslash.
  • In shell variable assignments, the expression must be enclosed in backticks.

2. Checking if a String is an Integer

expr works only with integers. When a non-integer is involved in an arithmetic operation, expr returns an error. By checking the exit code, we can determine if the input is an integer.

Principle

i=1
expr $i + 1 &> /dev/null
echo $?   # Returns 0 (success)

i=a
expr $i + 1 &> /dev/null
echo $?   # Returns 2 (error)

1 is an integer, so the command succeeds (exit code 0). a is not an integer, so the command fails (non-zero exit code).

Script Example

Save the following as /server/scripts/t3.sh:

#!/bin/bash
#no.1
[ $# -ne 2 ] && {
    echo "$0 please input NUM1 NUM2"
    exit 1   # Exactly two arguments required
}
#no.2
a=$1
b=$2
expr $a + $b &> /dev/null
if [ $? -ne 0 ]; then
    # Non-zero exit code indicates non-integer
    echo "You must input two integer numbers."
    exit 2
fi
#no.3
echo "a-b=$((a-b))"
echo "a+b=$((a+b))"
echo "a*b=$((a*b))"
echo "a/b=$((a/b))"
echo "a**b=$((a**b))"
echo "a%b=$((a%b))"

Execution Results

sh /server/scripts/t3.sh 2
# Output: /server/scripts/t3.sh please input NUM1 NUM2

sh /server/scripts/t3.sh a 1
# Output: You must input two integer numbers.

sh /server/scripts/t3.sh 2 1
# Output:
# a-b=0
# a+b=4
# a*b=4
# a/b=1
# a**b=4
# a%b=0

3. Checking File Extension with expr

We can use expr with pattern matching to verify if a filename ends with .pub.

Script Example

Save the following as /server/scripts/t5.sh:

#!/bin/bash
if expr "$1" : ".*\.pub" &> /dev/null; then
    echo "You are using $1"
else
    echo "Please use a .pub file"
fi

Execution Results

sh /server/scripts/t5.sh abd
# Output: Please use a .pub file

sh /server/scripts/t5.sh abd.pub
# Output: You are using abd.pub

4. Calculating String Length with expr

Use expr length to compute the length of a string. The example below filters words shorter than 6 characters.

Script Example

Save as /server/scripts/t6.sh:

for word in I am oldboy linux welcome to our training; do
    if [ "$(expr length "$word")" -le 6 ]; then
        echo "$word"
    fi
done

Execution Result

sh /server/scripts/t6.sh
# Output:
# I
# am
# oldboy
# linux
# to
# our

Tags: expr Shell bash String Manipulation integer arithmetic

Posted on Sat, 09 May 2026 13:26:19 +0000 by danoli3