Linux扩展篇-shell编程(五)-流程控制(一)-if语句

基本语法:

(1)单分支

if [ condition ];then
    statement(s)
fi

或

if [ condition ]
then
    statement(s)
fi

(2)多分支

if [ condition1 ]; then
    statement1(s)
elif [ condition2 ]; then
    statement2(s)
else
    statement3(s)
fi

注意事项:

  • if 开始 fi 结尾,当then和if在同一行的时候需要使用分号;不在同一行时,可直接输入。
  • [后面和]前面都必须要有空格
  • 对于变量的处理,需要加引号,以避免不必要的错误。没有加双引号会在一些含空格等的字符串变量判断的时候产生错误。比如 [ -n "$var" ],如果var为空会出错。
  • 不支持浮点数的判断
  • 未定义的变量,在使用-z或者-n来检查长度时,值也为0
  • 空变量未初始化的变量,在执行shell脚本时会出现意外报错,在使用前用-n或者-z进行判断。
  • $? 上一条命令执行的退出状态,可以用来作为判断。

实践:

(1)简单的判断

[root@kwephis1160698 ~]# a=25
[root@kwephis1160698 ~]# if[ $a -gt 18 ];then echo Ok; fi
-bash: syntax error near unexpected token `then'
[root@kwephis1160698 ~]# if[ $a -gt 18 ]; then echo Ok; fi
-bash: syntax error near unexpected token `then'
[root@kwephis1160698 ~]# if [ $a -gt 18 ]; then echo Ok; fi
Ok
[root@kwephis1160698 ~]# echo $a
25
[root@kwephis1160698 ~]# if [ $a -gt 18 ] && [ $a -lt 35 ]; then echo Ok; fi
Ok
[root@kwephis1160698 ~]# a=15
[root@kwephis1160698 ~]# if [ $a -gt 18 ] && [ $a -lt 35 ]; then echo Ok; fi
[root@kwephis1160698 ~]# 
[root@kwephis1160698 ~]# if [ $a -gt 18 && $a -lt 35 ]; then echo Ok; fi
-bash: [: missing `]'
[root@kwephis1160698 ~]# if [ $a -gt 18 -a $a -lt 35 ]; then echo Ok; fi
[root@kwephis1160698 ~]# a=25
[root@kwephis1160698 ~]# if [ $a -gt 18 -a $a -lt 35 ]; then echo Ok; fi
Ok

解析:
在 [ 中使用逻辑运算符,需要使用 -a(and)或者 -o(or)。
在 [[ 中使用逻辑运算符,需要使用 && 或者 ||。
(2)字符串判断优化

[root@kwephis1160698 ~]# vi if_test.sh
[root@kwephis1160698 ~]# 
#!/bin/bash

if [ $1 = hello ]
then
    echo "hello"
fi
[root@kwephis1160698 ~]# chmod  +x if_test.sh 
[root@kwephis1160698 ~]# ./if_test.sh 
./if_test.sh: line 3: [: =: unary operator expected

[root@kwephis1160698 ~]# vi if_test.sh 
[root@kwephis1160698 ~]# 
#!/bin/bash

if [ "$1"x = "hello"x ]
then
    echo "hello"
fi
[root@kwephis1160698 ~]# ./if_test.sh
[root@kwephis1160698 ~]# 

如果参数为空值,则程序会出现报错;建议,在字符串比较时,添加x,这样可以保证至少有一个字符可以比较。

posted @ 2023-06-27 10:02  cavan丶keke  阅读(90)  评论(0编辑  收藏  举报