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 neithernullnor0, otherwiseARG2ARG1 & ARG2:ARG1if neither argument isnullnor0, otherwise0ARG1 < ARG2:ARG1is less thanARG2ARG1 <= ARG2:ARG1is less than or equal toARG2ARG1 = ARG2:ARG1is equal toARG2ARG1 != ARG2:ARG1is unequal toARG2ARG1 >= ARG2:ARG1is greater than or equal toARG2ARG1 > ARG2:ARG1is greater thanARG2ARG1 + ARG2: arithmetic sum ofARG1andARG2ARG1 - ARG2: arithmetic difference ofARG1andARG2ARG1 * ARG2: arithmetic product ofARG1andARG2ARG1 / ARG2: arithmetic quotient ofARG1divided byARG2ARG1 % ARG2: arithmetic remainder ofARG1divided byARG2substrSTRING POS LENGTH: substring ofSTRING,POScounted from1indexSTRING CHARS: index inSTRINGwhere anyCHARSis found, or0length STRING: length ofSTRING+ TOKEN: interpretTOKENas a string, even if it is a keyword likematchor 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:
0ifEXPRESSIONis neithernullnor01ifEXPRESSIONisnullor02ifEXPRESSIONis syntactically invalid3if 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: