条件判断:
语法结构:
if [ 条件 ];then
command...
fi
++++++++++++++++++++++
if [ 条件 ];then
command...
else
command...
fi
++++++++++++++++++++++
if [ 条件1 ];then
command1...
elif [ 条件2 ];then
command2...
else
command3...
fi
++++++++++++++++++++++
if [ 条件1 ];then
command1...
if [ 条件2 ];then
command2...
fi
else
if [ 条件3 ];then
command3...
elif [ 条件4 ];then
command4...
else
command5...
fi
fi
man test
文件存在与否的判断
-e:是否存在;
-f:是否存在并且为普通文件
-d:是否存在并且为目录
-S:是否存在并且套接字文件
-p:
-c:
-b:
-L:
文件权限相关判断:
-r:
-w:
-x:
-u:是否有suid
-g:是否有sgid
-k:是否有t位
-s:是否为空白文件,-s表示非空;! -s 空文件
两个文件比较:
file1 -nt file2
file1 -ot file2
file1 -ef file2 比较file1和file2是否是同一个文件,也可以来判断是否为硬链接文件
整数比较:
-eq
-ne
-gt
-lt
-ge
-le
字符串比较:
-z
-n
string1 = string2
string1 != string2
多重条件判断:
-a 和 && 逻辑与 [ 条件1 -a 条件2 ] 条件1和条件2必须同时成立整个大条件才成立
-o 和 || 逻辑或 [ 条件1 -o 条件2 ] 条件1和条件2其中一个满足整个大条件就成立
! 非
优先级:
-a 和 && 大于 -o 和 || 大于 !
demo1:判断ip是否通
ping -c
$?
vim ping_ip.sh
#!/bin/bash
#Name:xxx
#Usage:xxx
#Update:
#Path:xxx
ping -c 2 10.1.1.254 > /dev/null 2>&1
if [ $? -eq 0 ];then
echo "$(date '+%F %T')the ip is ok" > /tmp/ip.log
else
echo "$(date '+%F %T')the is is not ok" >> /tmp/ip.log
fi
或
ping -c 2 $1 > /dev/null 2>&1
if [ $? -eq 0 ];then
echo "$(date '+%F %T')the ip is ok" > /tmp/ip.log
else
echo "$(date '+%F %T')the is is not ok" >> /tmp/ip.log
fi
或
read -p "Input your ip:" IP
ping -c 2 $IP > /dev/null 2>&1
if [ $? -eq 0 ];then
echo "$(date '+%F %T')the ip is ok" > /tmp/ip.log
else
echo "$(date '+%F %T')the is is not ok" >> /tmp/ip.log
fi
或者
read -p "Input your ip:" IP
ping -c 2 $IP > /dev/null 2>&1
[ $? -eq 0 ] && echo "$(date '+%F %T')the ip is ok" > /tmp/ip.log || echo "$(date '+%F %T')the is is not ok" >> /tmp/ip.log
或者
read -p "Input your ip:" IP
ping -c 2 $IP > /dev/null 2>&1
test $? -eq 0 && echo "$(date '+%F %T')the ip is ok" > /tmp/ip.log || echo "$(date '+%F %T')the is is not ok" >> /tmp/ip.log
demo2:判断一个进程是否存在
#!/bin/bash
ps -ef|grep vsftpd|grep -v 'grep' &>/dev/null
或者
# pgrep -l vsftpd
[ $? -eq 0 ] && echo "vsftpd ok" >>/tmp/log ||echo "vsftpd not ok" >>/tmp/log
demo3:判断一个服务是否正常
#!/bin/bash
wget -P /tmp http://localhost &>/dev/null
[ $? -ne 0 ] && echo "httpd not ok" >>/tmp/log ||echo "httpd is ok" >>/tmp/log
课堂练习:
1、写一个脚本判断一个用户是否存在
#!/bin/bash
read -p "Input your username:" user
id $user &>/dev/null
test $? -eq 0 && echo user is ok>>/tmp/user.log ||echo user is not ok >>/tmp/user.log
2、完善上第一个例子中给脚本传参时的bug,如果每个给脚本传参或者参数个数不等于1时,提示脚本的用法:usage:xxx.sh ip
if [ $# -ne 1 ];then
echo "Usage:`basename $0` IP";exit
fi
ping -c 2 $1 > /dev/null 2>&1
if [ $? -eq 0 ];then
echo "$(date '+%F %T')the ip is ok" > /tmp/ip.log
else
echo "$(date '+%F %T')the is is not ok"
shell 条件语句
最新推荐文章于 2024-01-24 22:55:22 发布