# expr

## PROLOG



           This manual page is part of the POSIX Programmer's Manual.  The
           Linux implementation of this interface may differ (consult the
           corresponding Linux manual page for details of Linux behavior), or
           the interface may not be implemented on Linux.
    


## NAME



           expr — evaluate arguments as an expression
    


## SYNOPSIS



           expr _operand_...
    


## DESCRIPTION



           The _expr_ utility shall evaluate an expression and write the result
           to standard output.
    


## OPTIONS



           None.
    


## OPERANDS



           The single expression evaluated by _expr_ shall be formed from the
           _operand_ operands, as described in the EXTENDED DESCRIPTION
           section. The application shall ensure that each of the expression
           operator symbols:
    
               (  )  |  &  =  >  >=  <  <=  !=  +  -  *  /  %  :
    
           and the symbols _integer_ and _string_ in the table are provided as
           separate arguments to _expr_.
    


## STDIN



           Not used.
    


## INPUT FILES



           None.
    


## ENVIRONMENT VARIABLES



           The following environment variables shall affect the execution of
           _expr_ :
    
           _LANG_      Provide a default value for the internationalization
                     variables that are unset or null. (See the Base
                     Definitions volume of POSIX.1‐2017, _Section 8.2_ ,
                     _Internationalization Variables_ for the precedence of
                     internationalization variables used to determine the
                     values of locale categories.)
    
           _LC_ALL_    If set to a non-empty string value, override the values
                     of all the other internationalization variables.
    
           _LC_COLLATE_
                     Determine the locale for the behavior of ranges,
                     equivalence classes, and multi-character collating
                     elements within regular expressions and by the string
                     comparison operators.
    
           _LC_CTYPE_  Determine the locale for the interpretation of sequences
                     of bytes of text data as characters (for example,
                     single-byte as opposed to multi-byte characters in
                     arguments) and the behavior of character classes within
                     regular expressions.
    
           _LC_MESSAGES_
                     Determine the locale that should be used to affect the
                     format and contents of diagnostic messages written to
                     standard error.
    
           _NLSPATH_   Determine the location of message catalogs for the
                     processing of _LC_MESSAGES_.
    


## ASYNCHRONOUS EVENTS



           Default.
    


## STDOUT



           The _expr_ utility shall evaluate the expression and write the
           result, followed by a <newline>, to standard output.
    


## STDERR



           The standard error shall be used only for diagnostic messages.
    


## OUTPUT FILES



           None.
    


## EXTENDED DESCRIPTION



           The formation of the expression to be evaluated is shown in the
           following table. The symbols _expr_ , _expr1_ , and _expr2_ represent
           expressions formed from _integer_ and _string_ symbols and the
           expression operator symbols (all separate arguments) by recursive
           application of the constructs described in the table. The
           expressions are listed in order of decreasing precedence, with
           equal-precedence operators grouped between horizontal lines. All
           of the operators shall be left-associative.
             ┌────────────────┬──────────────────────────────────────────┐
             │   **Expression** │               **Description** │
             ├────────────────┼──────────────────────────────────────────┤
             │ _integer_        │ An argument consisting only of an        │
             │                │ (optional) unary minus followed by       │
             │                │ digits.                                  │
             │ _string_         │ A string argument; see below.            │
             ├────────────────┼──────────────────────────────────────────┤
             │ ( _expr_ )       │ Grouping symbols. Any expression can be  │
             │                │ placed within parentheses.  Parentheses  │
             │                │ can be nested to a depth of              │
             │                │ {EXPR_NEST_MAX}.                         │
             ├────────────────┼──────────────────────────────────────────┤
             │ _expr1_ : _expr2_  │ Matching expression; see below.          │
             ├────────────────┼──────────────────────────────────────────┤
             │ _expr1_ * _expr2_  │ Multiplication of decimal integer-valued │
             │                │ arguments.                               │
             │ _expr1_ / _expr2_  │ Integer division of decimal integer-     │
             │                │ valued arguments, producing an integer   │
             │                │ result.                                  │
             │ _expr1_ % _expr2_  │ Remainder of integer division of decimal │
             │                │ integer-valued arguments.                │
             ├────────────────┼──────────────────────────────────────────┤
             │ _expr1_ + _expr2_  │ Addition of decimal integer-valued       │
             │                │ arguments.                               │
             │ _expr1_ - _expr2_  │ Subtraction of decimal integer-valued    │
             │                │ arguments.                               │
             ├────────────────┼──────────────────────────────────────────┤
             │                │ Returns the result of a decimal integer  │
             │                │ comparison if both arguments are         │
             │                │ integers; otherwise, returns the result  │
             │                │ of a string comparison using the locale- │
             │                │ specific collation sequence. The result  │
             │                │ of each comparison is 1 if the specified │
             │                │ relationship is true, or 0 if the        │
             │                │ relationship is false.                   │
             │ _expr1_ = _expr2_  │ Equal.                                   │
             │ _expr1_ > _expr2_  │ Greater than.                            │
             │ _expr1_ >= _expr2_ │ Greater than or equal.                   │
             │ _expr1_ < _expr2_  │ Less than.                               │
             │ _expr1_ <= _expr2_ │ Less than or equal.                      │
             │ _expr1_ != _expr2_ │ Not equal.                               │
             ├────────────────┼──────────────────────────────────────────┤
             │ _expr1_ & _expr2_  │ Returns the evaluation of _expr1_ if       │
             │                │ neither expression evaluates to null or  │
             │                │ zero; otherwise, returns zero.           │
             ├────────────────┼──────────────────────────────────────────┤
             │ _expr1_ | _expr2_  │ Returns the evaluation of _expr1_ if it is │
             │                │ neither null nor zero; otherwise,        │
             │                │ returns the evaluation of _expr2_ if it is │
             │                │ not null; otherwise, zero.               │
             └────────────────┴──────────────────────────────────────────┘
    
       **Matching Expression**
           The **':'** matching operator shall compare the string resulting from
           the evaluation of _expr1_ with the regular expression pattern
           resulting from the evaluation of _expr2_.  Regular expression syntax
           shall be that defined in the Base Definitions volume of
           POSIX.1‐2017, _Section 9.3_ , _Basic Regular Expressions_ , 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) and, therefore, it is
           unspecified whether **'^'** is a special character in that context.
           Usually, the matching operator shall return a string representing
           the number of characters matched (**'0'** on failure). Alternatively,
           if the pattern contains at least one regular expression
           subexpression **"[\(...\)]"** , the string matched by the back-
           reference expression **"\1"** shall be returned. If the back-reference
           expression **"\1"** does not match, then the null string shall be
           returned.
    
       **Identification as Integer or String**
           An argument or the value of a subexpression that consists only of
           an optional unary minus followed by digits is a candidate for
           treatment as an integer if it is used as the left argument to the
           _|_ operator or as either argument to any of the following
           operators: _& = > >= < <= != + - * / %_.  Otherwise, the argument or
           subexpression value shall be treated as a string.
    
           The use of string arguments **length** , **substr** , **index** , or **match**
           produces unspecified results.
    


## EXIT STATUS



           The following exit values shall be returned:
    
            0    The _expression_ evaluates to neither null nor zero.
    
            1    The _expression_ evaluates to null or zero.
    
            2    Invalid _expression_.
    
           >2    An error occurred.
    


## CONSEQUENCES OF ERRORS



           Default.
    
           _The following sections are informative._
    


## APPLICATION USAGE



           The _expr_ utility has a rather difficult syntax:
    
            *  Many of the operators are also shell control operators or
               reserved words, so they have to be escaped on the command
               line.
    
            *  Each part of the expression is composed of separate arguments,
               so liberal usage of <blank> characters is required. For
               example:
                       ┌──────────────────┬───────────────────────┐
                       │     **Invalid** │         **Valid** │
                       ├──────────────────┼───────────────────────┤
                       │ _expr_ 1+2         │ _expr_ 1 + 2            │
                       │ _expr_ "1 + 2"     │ _expr_ 1 + 2            │
                       │ _expr_ 1 + (2 * 3) │ _expr_ 1 + \( 2 \* 3 \) │
                       └──────────────────┴───────────────────────┘
    
           In many cases, the arithmetic and string features provided as part
           of the shell command language are easier to use than their
           equivalents in _expr_.  Newly written scripts should avoid _expr_ in
           favor of the new features within the shell; see _Section 2.5_ ,
           _Parameters and Variables_ and _Section 2.6.4_ , _Arithmetic Expansion_.
    
           After argument processing by the shell, _expr_ is not required to be
           able to tell the difference between an operator and an operand
           except by the value. If **"$a"** is **'='** , the command:
    
               expr "$a" = '='
    
           looks like:
    
               expr = = =
    
           as the arguments are passed to _expr_ (and they all may be taken as
           the **'='** operator). The following works reliably:
    
               expr "X$a" = X=
    
           Also note that this volume of POSIX.1‐2017 permits implementations
           to extend utilities. The _expr_ utility permits the integer
           arguments to be preceded with a unary minus. This means that an
           integer argument could look like an option.  Therefore, the
           conforming application must employ the **"--"** construct of Guideline
           10 of the Base Definitions volume of POSIX.1‐2017, _Section 12.2_ ,
           _Utility Syntax Guidelines_ to protect its operands if there is any
           chance the first operand might be a negative integer (or any
           string with a leading minus).
    
           For testing string equality the _test_ utility is preferred over
           _expr_ , as it is usually implemented as a shell built-in. However,
           the functionality is not quite the same because the _expr =_ and _!=_
           operators check whether strings collate equally, whereas _test_
           checks whether they are identical. Therefore, they can produce
           different results in locales where the collation sequence does not
           have a total ordering of all characters (see the Base Definitions
           volume of POSIX.1‐2017, _Section 7.3.2_ , _LC_COLLATE_).
    


## EXAMPLES



           The following command:
    
               a=$(expr "$a" + 1)
    
           adds 1 to the variable _a_.
    
           The following command, for **"$a"** equal to either **/usr/abc/file** or
           just **file** :
    
               expr $a : '.*/\(.*\)' \| $a
    
           returns the last segment of a pathname (that is, **file**).
           Applications should avoid the character **'/'** used alone as an
           argument; _expr_ may interpret it as the division operator.
    
           The following command:
    
               expr "//$a" : '.*/\(.*\)'
    
           is a better representation of the previous example. The addition
           of the **"//"** characters eliminates any ambiguity about the division
           operator and simplifies the whole expression. Also note that
           pathnames may contain characters contained in the _IFS_ variable and
           should be quoted to avoid having **"$a"** expand into multiple
           arguments.
    
           The following command:
    
               expr "X$VAR" : '.*' - 1
    
           returns the number of characters in _VAR_.
    


## RATIONALE



           In an early proposal, EREs were used in the matching expression
           syntax.  This was changed to BREs to avoid breaking historical
           applications.
    
           The use of a leading <circumflex> in the BRE is unspecified
           because many historical implementations have treated it as a
           special character, despite their system documentation. For
           example:
    
               expr foo : ^foo     expr ^foo : ^foo
    
           return 3 and 0, respectively, on those systems; their
           documentation would imply the reverse. Thus, the anchoring
           condition is left unspecified to avoid breaking historical scripts
           relying on this undocumented feature.
    


## FUTURE DIRECTIONS



           None.
    


* * *