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.

Apply the following rules to the Expression parameter:

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

A unary hyphen might precede the integers. 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. A \ (backslash) precedes the characters that need to be escaped. The items are listed in order of increasing precedence, with equal precedence operators grouped within { } (braces):

Table 1. Expression parameter operators and keywords
Item Description
Expression1 \| Expression2 Returns Expression1 if it is not a null value or a 0 value. Otherwise, it returns Expression2.
Expression1 \& Expression2 Returns Expression1 if both expressions are not a null value or 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 that results from the evaluation of Expression1 with the regular expression pattern that results from the evaluation of Expression2. Regular expression syntax is the same as the ed command, except that all patterns are anchored to the beginning of the string. 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 \), a string that contains the actual matched characters is returned.

A collating sequence can define equivalence classes for use in character ranges.

The following string arguments are extensions beyond the standards, and the behavior might be different across operating systems. These string arguments are NOT portable.

Table 2. String arguments
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:

Table 3. Exit status
Item Description
0 The Expression parameter does not evaluate to null or 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 expr X$a = Xj expression is also true.

Examples

  1. To modify a shell variable, enter the following command:
    COUNT=`expr $COUNT + 1`

    This command 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 it is used.

  2. To find the length of the $STR shell variable, enter the following command:
    LENGTH=`expr $STR : ".*"`

    This sets the LENGTH variable to the value given by the : (colon) operator. The pattern .* (dot, asterisk) matches any string from the beginning to end, so the colon operator gives the length of the $STR variable as the number of characters matched. The .* characters must be within quotation marks to prevent the shell from treating the * (asterisk) as a pattern-matching character. The quotations 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 error 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 command 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" : ".*"`

    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 recommended. Do not enclose shell variables in single quotation marks.

  3. To use part of a string, enter the following command:
    FLAG=`expr "$FLAG" : "-*\(.*\)"`

    This command removes leading hyphens, if any, from the $FLAG shell variable. The colon operator gives the part of the FLAG variable that is matched by the subexpression that is 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 error happens because the shell substitutes the value of the $FLAG variable before you run the expr command. The expr command does not know that the hyphen is the value of a variable. It can see only - : -*\(.*\) characters and it interprets the first hyphen as the subtraction operator. To eliminate this problem, use the following expression:

    FLAG=`expr "x$FLAG" : "x-*\(.*\)"`
  4. To use the expr command in an if statement, enter the following command:
    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 as = = =.

    The expr command interprets the = = = expression as three = operators in a row and displays a syntax error message. This error 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 the following command:
    expr length $SHELL 
    The following output is displayed:
    12
  7. To return the first position of where any character in the string de is found in abcdef, enter the following command:
    expr index abcdef de 
    The following output is displayed:
    4
  8. To return the first position of where any character in the string fd is found in abcdef, enter the following command:
    expr index abcdef fd
    The following output is displayed:
    4
  9. To return the string that starts at position 11, for a length of 6 of the string "Goodnight Ladies", enter the following command:
    expr substr "Goodnight Ladies" 11 6
    The following output is displayed:
    Ladies

Files

Table 4. Files
Item Description
/usr/bin/expr Contains the expr command.