一:利用test命令进行测试。关于某个文件类型的判断 , 比较常用
测试的标志 | 代表意义 |
1. 关于某个档名的『文件类型』判断,如 test -e filename 表示存在否 | |
-e | 该『档名』是否存在?(常用) test -e test04.sh && echo ‘exist’ || echo ‘not exist’ |
-f | 该『档名』是否存在且为文件(file)?(常用) test -f test04.sh && echo ‘exist’ || echo ‘not exist’ |
-d | 该『档名』是否存在且为目录(directory)?(常用) test -d test04.sh && echo ‘exist’ || echo ‘not exist’ |
-a 逻辑与(and), -o逻辑或(or)
关于两个整数之间的判定,例如 test n1 -eq n2 这个经常使用。用一两次就熟悉了
关於两个整数之间的判定,例如 test n1 -eq n2 | |
-eq | 两数值相等 (equal) |
-ne | 两数值不等 (not equal) |
shell 用来写上边生成值的条件判断,这个-eq 和-ne 非常有用!
二:利用判断符号 [ ]
我们还可以利用判断符号[ ] (就是中括号啦) 来进行数据的判断!
[ "$HOME" == "$MAIL" ] [□"$HOME"□==□"$MAIL"□] ↑ ↑ ↑ ↑ |
注意事项:
- 在中括号 [] 内的每个组件都需要有空白键来分隔;
- 在中括号内的变量,最好都以双引号括号起来;
- 在中括号内的常数,最好都以单或双引号括号起来。
[ “$test” == “$HOME” ] ;echo $?
下边自己随便写一个非常简单例子以供理解判断说明用法:(if []; then fi 用法后边补充说明,看一眼就会了!):
该sh脚本用来简单测试下web和ftp是否正常启动的, 首先使用webtest和ftptest获取变量内容,根据变量值进行判断输出。
#!/bin/bash
webtest=$(netstat -tunlp | grep “:80” )
ftptest=$(netstat -tnulp | grep “:21”)
echo $webtest //先输出看下内容
echo $ftptest
if [ “$webtest” != “” ]; then //判断说明,这个条件也可以用其他方式判断,比如if [ $webtest == “” ];then…就是后边的语句要修改了,反过来写。
echo “web is running! “
else
echo “web is not running!WEB is dead,please check! “
fi
if [ “$ftptest” != “” ]; then
echo “ftp is runing “
else
echo “ftp is dead,please check!”
fi
webtest=$(netstat -tunlp | grep “:80” )
ftptest=$(netstat -tnulp | grep “:21”)
echo $webtest //先输出看下内容
echo $ftptest
if [ “$webtest” != “” ]; then //判断说明,这个条件也可以用其他方式判断,比如if [ $webtest == “” ];then…就是后边的语句要修改了,反过来写。
echo “web is running! “
else
echo “web is not running!WEB is dead,please check! “
fi
if [ “$ftptest” != “” ]; then
echo “ftp is runing “
else
echo “ftp is dead,please check!”
fi
执行结果:
[root@aliserver ~]# sh test.sh
web test is : tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 1158/httpd tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1128/nginx
helloftp is : tcp 0 0 0.0.0.0:21 0.0.0.0:* LISTEN 1148/pure-ftpd (SER
web is running!
ftp is runing
[root@aliserver ~]# sh test.sh
web test is : tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 1158/httpd tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1128/nginx
helloftp is : tcp 0 0 0.0.0.0:21 0.0.0.0:* LISTEN 1148/pure-ftpd (SER
web is running!
ftp is runing
三:Shell script 的默认变量($0, $1…) 先了解。
script 是怎么达成这个功能的呢?其实 script 针对参数已经有配置好一些变量名称了!对应如下:
/path/to/scriptname opt1 opt2 opt3 opt4 $0 $1 $2 $3 $4 |
转载请注明:21运维 » shell学习笔记第四天(条件判断一)