1EXPR(1P)                   POSIX Programmer's Manual                  EXPR(1P)
2
3
4

PROLOG

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

NAME

12       expr — evaluate arguments as an expression
13

SYNOPSIS

15       expr operand...
16

DESCRIPTION

18       The expr utility shall evaluate an expression and write the  result  to
19       standard output.
20

OPTIONS

22       None.
23

OPERANDS

25       The  single expression evaluated by expr shall be formed from the oper‐
26       and operands, as described in the  EXTENDED  DESCRIPTION  section.  The
27       application shall ensure that each of the expression operator symbols:
28
29
30           (  )  |  &  =  >  >=  <  <=  !=  +  -  *  /  %  :
31
32       and  the  symbols integer and string in the table are provided as sepa‐
33       rate arguments to expr.
34

STDIN

36       Not used.
37

INPUT FILES

39       None.
40

ENVIRONMENT VARIABLES

42       The following environment variables shall affect the execution of expr:
43
44       LANG      Provide a default value for  the  internationalization  vari‐
45                 ables  that are unset or null. (See the Base Definitions vol‐
46                 ume of POSIX.1‐2017, Section 8.2, Internationalization  Vari‐
47                 ables  for  the  precedence of internationalization variables
48                 used to determine the values of locale categories.)
49
50       LC_ALL    If set to a non-empty string value, override  the  values  of
51                 all the other internationalization variables.
52
53       LC_COLLATE
54                 Determine  the locale for the behavior of ranges, equivalence
55                 classes, and multi-character collating elements within  regu‐
56                 lar expressions and by the string comparison operators.
57
58       LC_CTYPE  Determine  the  locale for the interpretation of sequences of
59                 bytes of text data as characters (for example, single-byte as
60                 opposed to multi-byte characters in arguments) and the behav‐
61                 ior of character classes within regular expressions.
62
63       LC_MESSAGES
64                 Determine the locale that should be used to affect the format
65                 and  contents  of  diagnostic  messages  written  to standard
66                 error.
67
68       NLSPATH   Determine the location of message catalogs for the processing
69                 of LC_MESSAGES.
70

ASYNCHRONOUS EVENTS

72       Default.
73

STDOUT

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

STDERR

79       The standard error shall be used only for diagnostic messages.
80

OUTPUT FILES

82       None.
83

EXTENDED DESCRIPTION

85       The formation of the expression to be evaluated is shown in the follow‐
86       ing  table.  The  symbols  expr, expr1, and expr2 represent expressions
87       formed from integer and string symbols and the expression operator sym‐
88       bols  (all  separate  arguments)  by  recursive application of the con‐
89       structs described in the table. The expressions are listed in order  of
90       decreasing  precedence, with equal-precedence operators grouped between
91       horizontal lines. All of the operators shall be left-associative.
92
93             ┌───────────────┬──────────────────────────────────────────┐
94Expression   Description                
95             ├───────────────┼──────────────────────────────────────────┤
96integer        │ An  argument  consisting  only   of   an │
97             │               │ (optional)  unary minus followed by dig‐ │
98             │               │ its.                                     │
99string         │ A string argument; see below.            │
100             ├───────────────┼──────────────────────────────────────────┤
101             │( expr )       │ Grouping symbols. Any expression can  be │
102             │               │ placed  within parentheses.  Parentheses │
103             │               │ can   be   nested   to   a   depth    of │
104             │               │ {EXPR_NEST_MAX}.                         │
105             ├───────────────┼──────────────────────────────────────────┤
106expr1 : expr2  │ Matching expression; see below.          │
107             ├───────────────┼──────────────────────────────────────────┤
108expr1 * expr2  │ Multiplication of decimal integer-valued │
109             │               │ arguments.                               │
110expr1 / expr2  │ Integer division of decimal integer-val‐ │
111             │               │ ued   arguments,  producing  an  integer │
112             │               │ result.                                  │
113expr1 % expr2  │ Remainder of integer division of decimal │
114             │               │ integer-valued arguments.                │
115             ├───────────────┼──────────────────────────────────────────┤
116expr1 + expr2  │ Addition of decimal integer-valued argu‐ │
117             │               │ ments.                                   │
118expr1 - expr2  │ Subtraction  of  decimal  integer-valued │
119             │               │ arguments.                               │
120             ├───────────────┼──────────────────────────────────────────┤
121             │               │ Returns  the result of a decimal integer │
122             │               │ comparison if both arguments  are  inte‐ │
123             │               │ gers; otherwise, returns the result of a │
124             │               │ string comparison using the  locale-spe‐ │
125             │               │ cific  collation sequence. The result of │
126             │               │ each comparison is 1  if  the  specified │
127             │               │ relationship  is true, or 0 if the rela‐ │
128             │               │ tionship is false.                       │
129expr1 = expr2  │ Equal.                                   │
130expr1 > expr2  │ Greater than.                            │
131expr1 >= expr2 │ Greater than or equal.                   │
132expr1 < expr2  │ Less than.                               │
133expr1 <= expr2 │ Less than or equal.                      │
134expr1 != expr2 │ Not equal.                               │
135             ├───────────────┼──────────────────────────────────────────┤
136expr1 & expr2  │ Returns the evaluation of expr1 if  nei‐ │
137             │               │ ther  expression  evaluates  to  null or │
138             │               │ zero; otherwise, returns zero.           │
139             ├───────────────┼──────────────────────────────────────────┤
140expr1 | expr2  │ Returns the evaluation of expr1 if it is │
141             │               │ neither   null   nor   zero;  otherwise, │
142             │               │ returns the evaluation of expr2 if it is │
143             │               │ not null; otherwise, zero.               │
144             └───────────────┴──────────────────────────────────────────┘
145   Matching Expression
146       The  ':'  matching operator shall compare the string resulting from the
147       evaluation of expr1 with the regular expression pattern resulting  from
148       the  evaluation  of  expr2.   Regular  expression  syntax shall be that
149       defined in the Base Definitions volume of  POSIX.1‐2017,  Section  9.3,
150       Basic Regular Expressions, except that all patterns are anchored to the
151       beginning of the string (that is, only sequences starting at the  first
152       character  of  a  string  are  matched  by the regular expression) and,
153       therefore, it is unspecified whether '^' is a special character in that
154       context.  Usually,  the  matching operator shall return a string repre‐
155       senting the number of characters matched  ('0'  on  failure).  Alterna‐
156       tively,  if the pattern contains at least one regular expression subex‐
157       pression "[\(...\)]", the string matched by the back-reference  expres‐
158       sion "\1" shall be returned. If the back-reference expression "\1" does
159       not match, then the null string shall be returned.
160
161   Identification as Integer or String
162       An argument or the value of a subexpression that consists  only  of  an
163       optional unary minus followed by digits is a candidate for treatment as
164       an integer if it is used as the left argument to the | operator  or  as
165       either argument to any of the following operators: & = > >= < <= != + -
166       * / %.  Otherwise, the argument or subexpression value shall be treated
167       as a string.
168
169       The  use  of  string arguments length, substr, index, or match produces
170       unspecified results.
171

EXIT STATUS

173       The following exit values shall be returned:
174
175        0    The expression evaluates to neither null nor zero.
176
177        1    The expression evaluates to null or zero.
178
179        2    Invalid expression.
180
181       >2    An error occurred.
182

CONSEQUENCES OF ERRORS

184       Default.
185
186       The following sections are informative.
187

APPLICATION USAGE

189       The expr utility has a rather difficult syntax:
190
191        *  Many of the operators are also shell control operators or  reserved
192           words, so they have to be escaped on the command line.
193
194        *  Each  part  of the expression is composed of separate arguments, so
195           liberal usage of <blank> characters is required. For example:
196
197                       ┌─────────────────┬───────────────────────┐
198Invalid      Valid         
199                       ├─────────────────┼───────────────────────┤
200expr 1+2         │ expr 1 + 2            │
201expr "1 + 2"     │ expr 1 + 2            │
202expr 1 + (2 * 3) │ expr 1 + \( 2 \* 3 \) │
203                       └─────────────────┴───────────────────────┘
204       In many cases, the arithmetic and string features provided as  part  of
205       the  shell command language are easier to use than their equivalents in
206       expr.  Newly written scripts should avoid expr in favor of the new fea‐
207       tures  within  the shell; see Section 2.5, Parameters and Variables and
208       Section 2.6.4, Arithmetic Expansion.
209
210       After argument processing by the shell, expr is not required to be able
211       to tell the difference between an operator and an operand except by the
212       value. If "$a" is '=', the command:
213
214
215           expr "$a" = '='
216
217       looks like:
218
219
220           expr = = =
221
222       as the arguments are passed to expr (and they all may be taken  as  the
223       '=' operator). The following works reliably:
224
225
226           expr "X$a" = X=
227
228       Also  note  that this volume of POSIX.1‐2017 permits implementations to
229       extend utilities. The expr utility permits the integer arguments to  be
230       preceded  with a unary minus. This means that an integer argument could
231       look like an option.  Therefore, the conforming application must employ
232       the  "--"  construct  of Guideline 10 of the Base Definitions volume of
233       POSIX.1‐2017, Section 12.2, Utility Syntax Guidelines  to  protect  its
234       operands  if  there is any chance the first operand might be a negative
235       integer (or any string with a leading minus).
236
237       For testing string equality the test utility is preferred over expr, as
238       it is usually implemented as a shell built-in. However, the functional‐
239       ity is not quite the same because the expr =  and  !=  operators  check
240       whether  strings  collate equally, whereas test checks whether they are
241       identical. Therefore, they can produce  different  results  in  locales
242       where  the  collation  sequence  does  not have a total ordering of all
243       characters (see the Base Definitions volume  of  POSIX.1‐2017,  Section
244       7.3.2, LC_COLLATE).
245

EXAMPLES

247       The following command:
248
249
250           a=$(expr "$a" + 1)
251
252       adds 1 to the variable a.
253
254       The  following  command, for "$a" equal to either /usr/abc/file or just
255       file:
256
257
258           expr $a : '.*/\(.*\)' \| $a
259
260       returns the last segment of a pathname (that is,  file).   Applications
261       should  avoid  the  character  '/'  used alone as an argument; expr may
262       interpret it as the division operator.
263
264       The following command:
265
266
267           expr "//$a" : '.*/\(.*\)'
268
269       is a better representation of the previous example. The addition of the
270       "//"  characters  eliminates  any ambiguity about the division operator
271       and simplifies the whole expression. Also note that pathnames may  con‐
272       tain  characters  contained in the IFS variable and should be quoted to
273       avoid having "$a" expand into multiple arguments.
274
275       The following command:
276
277
278           expr "X$VAR" : '.*' - 1
279
280       returns the number of characters in VAR.
281

RATIONALE

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

FUTURE DIRECTIONS

299       None.
300

SEE ALSO

302       Section 2.5, Parameters and Variables, Section 2.6.4, Arithmetic Expan‐
303       sion
304
305       The Base Definitions volume of POSIX.1‐2017, Section 7.3.2, LC_COLLATE,
306       Chapter 8, Environment Variables, Section 9.3,  Basic  Regular  Expres‐
307       sions, Section 12.2, Utility Syntax Guidelines
308
310       Portions  of  this text are reprinted and reproduced in electronic form
311       from IEEE Std 1003.1-2017, Standard for Information Technology --  Por‐
312       table  Operating System Interface (POSIX), The Open Group Base Specifi‐
313       cations Issue 7, 2018 Edition, Copyright (C) 2018 by the  Institute  of
314       Electrical  and  Electronics Engineers, Inc and The Open Group.  In the
315       event of any discrepancy between this version and the original IEEE and
316       The  Open Group Standard, the original IEEE and The Open Group Standard
317       is the referee document. The original Standard can be  obtained  online
318       at http://www.opengroup.org/unix/online.html .
319
320       Any  typographical  or  formatting  errors that appear in this page are
321       most likely to have been introduced during the conversion of the source
322       files  to  man page format. To report such errors, see https://www.ker
323       nel.org/doc/man-pages/reporting_bugs.html .
324
325
326
327IEEE/The Open Group                  2017                             EXPR(1P)
Impressum