The expr
command calculates the given expression and displays its corresponding output. It is used for basic operations such as addition, subtraction, multiplication, division, and modulus on integers, evaluating regular expressions, and string operations such as substring and string length.
expr [EXPRESSION | OPTION]
--help
: Output help information.--version
: Output version information.
ARG1 | ARG2
:ARG1
if it is neithernull
nor0
, otherwiseARG2
.ARG1 & ARG2
:ARG1
if both arguments are neithernull
nor0
, otherwise0
.ARG1 < ARG2
:ARG1
is less thanARG2
.ARG1 <= ARG2
:ARG1
is less than or equal toARG2
.ARG1 = ARG2
:ARG1
is equal toARG2
.ARG1 != ARG2
:ARG1
is not equal toARG2
.ARG1 >= ARG2
:ARG1
is greater than or equal toARG2
.ARG1 > ARG2
:ARG1
is greater thanARG2
.ARG1 + ARG2
: Arithmetic sum ofARG1
andARG2
.ARG1 - ARG2
: Arithmetic difference ofARG1
andARG2
.ARG1 * ARG2
: Arithmetic product ofARG1
andARG2
.ARG1 / ARG2
: Arithmetic quotient ofARG1
divided byARG2
.ARG1 % ARG2
: Arithmetic remainder ofARG1
divided byARG2
.STRING : REGEXP
: Pattern match of the regular expressionREGEXP
inSTRING
.match STRING REGEXP
: Same asSTRING
matchingREGEXP
.substr STRING POS LENGTH
: Substring ofSTR
starting atPOS
, which starts counting from1
.index STRING CHARS
: Index of any ofCHARS
inSTRING
, or0
if not found.length STRING
: Length of the string.+ TOKEN
: TreatTOKEN
as a string, even if it is a keyword likematch
or an operator like/
.(EXPRESSION)
: Value ofEXPRESSION
.
Calculate 12 + 9
.
expr 12 + 9
# 21
Calculate 12 * 2
.
expr 12 \* 2
# 24
Perform operations on variables in a shell
script. Remember to save it as a .sh
file, grant it 755
permission, and then execute.
echo "Enter two numbers"
read x
read y
sum=`expr $x + $y`
echo "Sum = $sum"
https://github.com/WindrunnerMax/EveryDay
https://www.computerhope.com/unix/uexpr.htm
https://www.runoob.com/linux/linux-comm-expr.html
https://www.geeksforgeeks.org/expr-command-in-linux-with-examples/