美文网首页程序员
Linux Shell之if语法和常用场景

Linux Shell之if语法和常用场景

作者: 唯米天空 | 来源:发表于2020-05-26 11:50 被阅读0次

1. 语法

1.1. 标准语法

if 条件
then
    command1
else
    command2
fi

如果没写fi,报错信息:

test.sh: line 14: syntax error: unexpected end of fi

1.2. 简练语法

条件 && 命令
条件 || 命令

比如

[ -f "/etc/shadow" ] && echo "This computer uses shadow passwors"
&& 如果是“前面”,则“后面”
[ -f /var/run/dhcpd.pid ] && rm /var/run/dhcpd.pid    检查 文件是否存在,如果存在就删掉
   ||   如果不是“前面”,则后面
[ -f /usr/sbin/dhcpd ] || exit 0    检验文件是否存在,如果存在就退出

当条件返回为true,这里的true的意思是条件返回为0.返回为0,跟其他语言语法不一样,正好相反。

2. 三种 “条件” 方式

2.1. 方式一

if
    command
then
    command1
else
    command2
fi

if command 等价于 command+if $?

$?表示上一条命令返回结果

[xrepos@repos wdog]$ hahaha
-bash: hahaha: command not found
[xrepos@repos wdog]$ echo $?
127
[xrepos@repos wdog]$ ls
[xrepos@repos wdog]$ echo $?
0
if
 函数
then

命令执行成功,等于返回0 (比如grep ,找到匹配)
执行失败,返回非0 (grep,没找到匹配)

2.2. 方式二

if [ expression_r_r_r  ]
then

表达式结果为真,则返回0,if把0值引向then

2.3. 方式三

if test expression_r_r_r
then

表达式结果为假,则返回非0,if把非0值引向then

3. 条件表达式(重点)

3.1. 基本

文件表达式
if [ -f  file ]    如果文件存在
if [ -d ...   ]    如果目录存在
if [ -s file  ]    如果文件存在且非空 
if [ -r file  ]    如果文件存在且可读
if [ -w file  ]    如果文件存在且可写
if [ -x file  ]    如果文件存在且可执行   
整数变量表达式
if [ int1 -eq int2 ]    如果int1等于int2   
if [ int1 -ne int2 ]    如果不等于    
if [ int1 -ge int2 ]       如果>=
if [ int1 -gt int2 ]       如果>
if [ int1 -le int2 ]       如果<=
if [ int1 -lt int2 ]       如果<
   
   字符串变量表达式
If  [ $a = $b ]                 如果string1等于string2
                                字符串允许使用赋值号做等号
if  [ $string1 !=  $string2 ]   如果string1不等于string2       
if  [ -n $string  ]             如果string 非空(非0),返回0(true)  
if  [ -z $string  ]             如果string 为空
if  [ $sting ]                  如果string 非空,返回0 (和-n类似)

Tips:

  • -eq -ne -lt -nt只能用于整数,不适用于字符串,字符串等于用赋值号=

  • =放在别的地方是赋值,放在if [ ] 里就是字符串等于,shell里面没有==的,那是c语言的等于

  • 无空格的字符串,可以加" ",也可以不加

if [ $a = 123 ] ; then
echo equal123
fi
  • = 作为等于时,其两边都必须加空格,否则失效
    等号也是操作符,必须和其他变量,关键字,用空格格开

(等号做赋值号时正好相反,两边不能有空格)

  • If [ $ANS ] 等价于 if [ -n $ANS ]

  • 整数条件表达式,大于,小于,shell里没有> 和< ,会被当作尖括号,只有-ge,-gt,-le,lt

  • 整数操作符号-ge,-gt,-le,-lt, 别忘了加-

3.2. 逻辑组合

  • 逻辑非 !
if [ ! -d $num ] 
#如果不存在目录$num
  • 逻辑与 -a
if [ 表达式1  –a  表达式2 ]
  • 逻辑或 -o
if [ 表达式1  –o 表达式2 ]

参考链接

http://blog.sina.com.cn/s/blog_64e166580100vwk2.html


相关文章

网友评论

    本文标题:Linux Shell之if语法和常用场景

    本文链接:https://www.haomeiwen.com/subject/onumahtx.html