if 判断的几种用法
2016-10-09
if 判断的几种用法
(1)和文档相关的判断:
shell 脚本中 if 还经常判断关于文档属性,比如判断是普通文件还是目录,判断文件是否有读写执行权限等。常用的也就几个选项:
-e
:判断文件或目录是否存在
-d
:判断是不是目录,并是否存在
-f
:判断是否是普通文件,并存在
-r
:判断文档是否有读权限
-w
:判断文档是否有写权限
-x
:判断文档是否有执行权限
-s
: 判断文件是否存在且是否为空
以上用法其实是 if 结合 test 命令来完成的
使用 if 判断时,具体格式是:
if [ -e filename ];then
例子:
[root@133 ~]# if [ -e /home/ ];then echo ok;fi
ok
[root@133 ~]# if [ -d /home/ ];then echo ok;fi
ok
[root@133 ~]# if [ -f /home/ ];then echo ok;fi
[root@133 ~]# if [ -f /root/1.txt ];then echo ok;fi
ok
[root@133 ~]# if [ -r /root/1.txt ];then echo ok;fi
ok
[root@133 ~]# if [ -w /root/1.txt ];then echo ok;fi
ok
[root@133 ~]# if [ -x /root/1.txt ];then echo ok;fi
[root@133 ~]# if [ -x /home/ ];then echo ok;fi
ok
(2)变量是否为空
有时候,我们需要判断一个变量的值是否为空,以避免后续操作产生异样。假如我们不去判断变量是否有值,就接着在后续命令中引用该变量,则会出错。比如,下面的脚本。
[root@133 ~]# cat li.sh
#!/bin/bash
n=`wc -l 1.txt|awk '{print $1}'`
if [ $n -gt 10 ]
then
echo "The file 1.txt has more than 10 lines."
fi
这个脚本乍一看没有问题,但我们没有考虑到 1.txt 文件不存在的情况,如果文件不存在,那么 n 的值也是不存在的,后面的判断也会出错。所以应该先判断一下 n 是否为空。使用下面的方法:
[root@133 ~]# a=1
[root@133 ~]# if [ -n "$a" ];then echo "a is not null";else echo "a is null";fi
a is not null
[root@133 ~]# a=
[root@133 ~]# if [ -n "$a" ];then echo "a is not null";else echo "a is null";fi
a is null
-n 选项可以判断一个变量是否不为空,注意一定要把变量引起来,本例中我们用双引号把 $a 引起来了,否则是不对的。还有一个和 -n 正好相对的, -z ,用法如下。
[root@133 ~]# a=
[root@133 ~]# if [ -z $a ];then echo "a is null";fi
a is null
这个 -z 后面的 $a 不用加双引号。
(3)if 判断条件可以是一条命令
[root@133 ~]# if grep -q '^mysql:' /etc/passwd;then echo "user mysql exist.";fi
user mysql exist.
grep -q 选项的作用是,过滤但不输出。用在 if 判断中,我们不需要输出结果,只需要知道它是否执行成功,也就是说如果 /etc/passwd 文件中含有 MySQL 这个用户,那么这个条件就成立了。