Home > php教程 > PHP开发 > The use of expr in Shell

The use of expr in Shell

高洛峰
Release: 2016-11-19 11:21:59
Original
2066 people have browsed it

1.expr command is generally used for integer values. Its general format is:
expr argument operator argument
The general usage is to use expr to do arithmetic operations, such as:
[root@centos ~]# expr 10 + 20
30
$ expr 30 / 3 / 2
5
(Note that there are spaces around the operator, if there are no spaces, it means string concatenation)
When using the multiplication sign, its specific meaning must be masked with a backslash. Because the shell may misunderstand the meaning of the asterisk. For example:
[root@centos ~]# expr 10 * 10 //: Error,
expr: syntax error
[root@centos ~]# expr 10 * 10 //Correct
100
2. Use expr to import the output /dev/null can be used for judgment.
If the expression is successful, it can be expressed as follows:
$value=12
$expr $value + 10 > /dev/null 2>&1
$echo $?
0

If the expression fails, a non-zero value is returned
$value=hello
$expr $value + 10 > /dev/null 2>&1
$echo $?
2
3.expr also operates on strings
String comparison:
expr If successful, return value 1 , any other value is invalid or an error. For example, the following example tests whether two strings are equal, where the strings are "hello" and hello".
$value=hello
$expr $value = "hello"
1
#The return value of the shell at this time is 0.
$echo $?
0
4.expr pattern matching:
Regarding expr pattern matching, you can use expr to specify the string pattern matching by specifying the colon: option. .* represents any
character repeated 0 or more times. . The return value is the content in parentheses. For example, in tomcat's catalina.sh, expr pattern matching is used to obtain the real path of the connection file. The example is as follows:
# resolve links - $0 may be a softlink
PRG="$0 "
while [ -h "$PRG" ]; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> .*$'` # expr here The return value is the real path of the connection file
if expr "$link" : '/.*' > /dev/null; then #The path name returns 1
PRG="$link"
else
PRG=`dirname "$ PRG"`/"$link"
fi
done

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template