expr command in UNIX
expr EXPRESSIONexpr OPTIONIntroduction
Section titled “Introduction”expr command evaluates arithmetical expressions taking string arguments.
Options
Section titled “Options”expr command print the value of EXPRESSION to standard output.
EXPRESSION may be:
- ARG1 | ARG2:- ARG1if it is neither- nullnor- 0, otherwise- ARG2
- ARG1 & ARG2:- ARG1if neither argument is- nullnor- 0, otherwise- 0
- ARG1 < ARG2:- ARG1is less than- ARG2
- ARG1 <= ARG2:- ARG1is less than or equal to- ARG2
- ARG1 = ARG2:- ARG1is equal to- ARG2
- ARG1 != ARG2:- ARG1is unequal to- ARG2
- ARG1 >= ARG2:- ARG1is greater than or equal to- ARG2
- ARG1 > ARG2:- ARG1is greater than- ARG2
- ARG1 + ARG2: arithmetic sum of- ARG1and- ARG2
- ARG1 - ARG2: arithmetic difference of- ARG1and- ARG2
- ARG1 * ARG2: arithmetic product of- ARG1and- ARG2
- ARG1 / ARG2: arithmetic quotient of- ARG1divided by- ARG2
- ARG1 % ARG2: arithmetic remainder of- ARG1divided by- ARG2
- substr- STRING POS LENGTH: substring of- STRING,- POScounted from- 1
- index- STRING CHARS: index in- STRINGwhere any- CHARSis found, or- 0
- length STRING: length of- STRING
- + TOKEN: interpret- TOKENas a string, even if it is a keyword like- matchor an operator like- /
Beware that many operators need to be escaped or quoted for shells.
Comparisons are arithmetic if both ARGs are numbers, else lexicographical.
Pattern matches return the string matched between \( and \) or null.
If \( and \) are not used, they return the number of characters matched or 0.
Exit status is:
- 0if- EXPRESSIONis neither- nullnor- 0
- 1if- EXPRESSIONis- nullor- 0
- 2if- EXPRESSIONis syntactically invalid
- 3if an error occurred
Examples
Section titled “Examples”Logical
Section titled “Logical”expr 3 '|' 23 # ARG1 is not null nor 0
expr 0 '|' 22 # ARG1 is 0
expr 0 '&' 20 # ARG1 is 0
expr 4 '&' 24 # ARG1 and ARG2 are not null nor 0
expr 4 '&' 00 # ARG2 is 0
 expr 4 '&' ''0 # ARG2 is nullComparison
Section titled “Comparison”# like '==' in most programming languagesexpr 55 = 230 # return 0: given numbers are not equal
expr 55 = 551 # return 1: given numbers are equal
expr 3 '<' 20 # return 0: left-side number is not minor than right-side number
expr 3 '>' 21 # return 1: left-side number is major than right-side numberArithmetical
Section titled “Arithmetical”expr 55 + 96 - 23128
a=82; b="$a + 6"; echo $b82 + 6
expr $b88
expr $a - $b6String
Section titled “String”# evaluate the length of a stringexpr length "Hello, World!"13
# extract substrings from string variableshello="HelloWorld"expr substr $hello 3 4lloW
# in sh and bash index starts at 1expr index $hello W6Quotes
Section titled “Quotes”Manual reference: