expr Command

Purpose

Evaluates arguments as expressions.

Syntax

expr Expression

Description

The expr command reads the Expression parameter, evaluates it, and writes the result to standard output.

You must apply the following rules to the Expression parameter:

  • Separate each term with blanks.
  • Precede characters special to the shell with a \ (backslash).
  • Quote strings containing blanks or other special characters.

Integers may be preceded by a unary hyphen. Internally, integers are treated as 32-bit, twos complement numbers.

Note: The expr command returns 0 to indicate a zero value, rather than the null string.

The following items describe Expression parameter operators and keywords. Characters that need to be escaped are preceded by a \ (backslash). The items are listed in order of increasing precedence, with equal precedence operators grouped within { } (braces):

Item Description
Expression1 \| Expression2 Returns Expression1 if it is neither a null value nor a 0 value; otherwise, it returns Expression2.
Expression1 \& Expression2 Returns Expression1 if both expressions are neither a null value nor a 0 value; otherwise, it returns a value of 0.
Expression1 { =, \>, \>=, \<, \<=, != } Expression2 Returns the result of an integer comparison if both expressions are integers; otherwise, it returns the result of a string comparison.
Expression1 {+, - } Expression2 Adds or subtracts integer-valued arguments.
Expression1 { \*, /, % } Expression2 Multiplies, divides, or provides the remainder from the division of integer-valued arguments.
Expression1 : Expression2 Compares the string resulting from the evaluation of Expression1 with the regular expression pattern resulting from the evaluation of Expression2. Regular expression syntax is the same as that of the ed command, except that all patterns are anchored to the beginning of the string (that is, only sequences starting at the first character of a string are matched by the regular expression). Therefore, a ^ (caret) is not a special character in this context.

Normally the matching operator returns the number of characters matched (0 on failure). If the pattern contains a subexpression, that is:

\( Expression \)

then a string containing the actual matched characters is returned.

A collating sequence can define equivalence classes for use in character ranges. See "Understanding Locale Environment Variables" in Globalization Guide and Reference for more information on collating sequences and equivalence classes.

Note: The following string arguments are extensions beyond that of the standards, and the behavior may be different across operating systems. These string arguments are NOT portable.

Item Description
match String1 String2 Same as Expression1 : Expression2.
length String1 Returns the length of the String1.
index String1 String2 Returns the first position in String1 where any character in String2 exists.
substr String1 StartPosition Length                        Returns a string that starts with the character at StartPosition in String1 and continuies for Length characters

Exit Status

This command returns the following exit values:

Item Description
0 The Expression parameter evaluates to neither null nor 0.
1 The Expression parameter evaluates to null or 0.
2 The Expression parameter is not valid.
>2 An error occurred.

Note: After parameter processing by the shell, the expr command cannot distinguish between an operator and an operand except by the value. Thus, if the value of $a is j, the command:

expr $a = j

looks like:

expr j = j

after the shell passes the arguments to the expr command. The following is also true:

expr X$a = Xj

Examples

  1. To modify a shell variable, enter:
    COUNT=`expr $COUNT + 1`
    This adds 1 to the shell variable $COUNT. The expr command is enclosed in grave accents, which causes the shell to substitute the standard output from the expr command into the COUNT= command. The $COUNT variable must be initialized before using.
  2. To find the length of the $STR shell variable, enter:
    LENGTH=`expr $STR : ".*"`
    This sets the LENGTH variable to the value given by the: (colon) operator. The pattern .* (dot, asterisk) matches any string from beginning to end, so the colon operator gives the length of the $STR variable as the number of characters matched. Note that .* must be within quotes to prevent the shell from treating the * (asterisk) as a pattern-matching character. The quotes are not part of the pattern.

    If the $STR variable is set to the null string or contains any white space (blanks or tabs), then the command displays the error message expr: syntax error. This happens because the shell does not normally pass null strings to commands. In this case, the expr command sees only:

    :.*
    The shell also removes the single quotation marks. This does not work because the colon operator requires two values. The problem is fixed by enclosing the shell variable in double quotation marks:
    LENGTH=`expr "$STR" : ".*"`
    Now if the value of the $STR variable is null, the LENGTH variable is set to a value of 0. Enclosing shell variables in double quotation marks is generally recommended. Do not enclose shell variables in single quotation marks.
  3. To use part of a string, enter:
    FLAG=`expr "$FLAG" : "-*\(.*\)"`
    This removes leading hyphens, if any, from the $FLAG shell variable. The colon operator gives the part of the FLAG variable matched by the subexpression enclosed between \( and \) characters (backslash, open parenthesis and backslash, close parenthesis). If you omit the \( and \) subexpression characters, the colon operator gives the number of characters matched.

    If the $FLAG variable is set to - (hyphen), the command displays a syntax error message. This happens because the shell substitutes the value of the $FLAG variable before running the expr command. The expr command does not know that the hyphen is the value of a variable. It can only see:

    - : -*\(.*\)
    and it interprets the first hyphen as the subtraction operator. To eliminate this problem, use:
    FLAG=`expr "x$FLAG" : "x-*\(.*\)"`
  4. To use the expr command in an if statement, enter:
    if expr "$ANSWER" : "[yY]" >/dev/null
    then
    echo ANSWER begins with "y" or "Y"
    fi
    If the $ANSWER variable begins with y or Y, the then part of the if statement is performed. If the match succeeds, the result of the expression is 1 and the expr command returns an exit value of 0, which is recognized as the logical value True by the if statement. If the match fails, the result is 0 and the exit value 1 (False).

    Redirecting the standard output of the expr command to the /dev/null special file discards the result of the expression. If you do not redirect it, the result is written to the standard output, which is usually your workstation display.

  5. Consider the following expression:
    expr "$STR" = "="
    If the $STR variable has the value = (equal sign), then after the shell processes this command the expr command sees the expression:
    = = =
    The expr command interprets this as three = operators in a row and displays a syntax error message. This happens whenever the value of a shell variable is the same as that of one of the expr operators. You can avoid this problem by phrasing the expression as:
    expr "x$STR" = "x="
  6. To return the length of the $SHELL environment variable, /usr/bin/ksh, enter:
    expr length $SHELL
    The following is displayed:
    12
  7. To return the first position of where any characters in the string "de" is found in "abcdef", enter:
    expr index abcdef de
    The following is displayed:
    4
  8. To return the first position of where any characters in the string "fd" is found in "abcdef", enter:
    expr index abcdef fd
    The following is displayed:
    4
  9. To return the string starting at position 11, for a length of 6 of the string "Goodnight Ladies", enter:
    expr substr "Goodnight Ladies" 11 6
    The following is displayed:
    Ladies

Files

Item Description
/usr/bin/expr Contains the expr command.