Expr

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search

Template:Lowercase Script error: No such module "Infobox".Template:Template otherScript error: No such module "Check for unknown parameters".Template:Main other expr is a command line utility on Unix and Unix-like operating systems which evaluates an expression and outputs the corresponding value. It first appeared in Unix v7. The command is available for Microsoft Windows as part of the UnxUtils collection[1] of native Win32 ports of common GNU Unix-like utilities.[2] The Template:Mono command has also been ported to the IBM i operating system.[3]

Overview

expr evaluates integer or string expressions, including pattern matching regular expressions. Each symbol (operator, value, etc.) in the expression must be given as a separate parameter. Most of the challenge posed in writing expressions is preventing the invoking command line shell from acting on characters intended for expr to process.

Syntax

Syntax: Template:Mono

The operators available

  • for integers: addition, subtraction, multiplication, division and modulus
  • for strings: match a regular expression; in some versions: find a set of characters in a string ("index"), find substring ("substr"), length of string ("length")
  • for either: comparison (equal, not equal, less than, etc.)

Example

The following is a (non-POSIX-compliant) example involving Boolean expressions:

expr length  "abcdef"  "<"  5  "|"  15  -  4  ">"  8

This example outputs "1". This is because length "abcdef" is 6, which is not less than 5 (so the left side of the | returns zero). But 15 minus 4 is 11 and is greater than 8, so the right side is true, which makes the or true, so 1 is the result. The program exit status is zero for this example.

For pure arithmetic, it is often more convenient to use bc. For example:

echo "3 * 4 + 14 / 2" | bc

since it accepts the expression as a single argument.

For portable shell programming, use of the "index", "length", "match" and "substr" commands must be avoided; string matching remains possible but it must use the "string : regexp" syntax.

See also

References

Template:Reflist

External links

Template:Sister project

Script error: No such module "Navbox". Template:Core Utilities commands

Template:Asbox

  1. Port of the most important GNU utilities to Windows
  2. Script error: No such module "citation/CS1".
  3. Script error: No such module "citation/CS1".