shell 条件语句

来源:互联网 发布:java图片转化为base64 编辑:程序博客网 时间:2024/06/08 06:34
条件判断:语法结构: 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...   fielse   if [ 条件3 ];then    command3...   elif [ 条件4 ];then    command4...   else     command5...  fifiman 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 file2file1 -ef file2 比较file1和file2是否是同一个文件,也可以来判断是否为硬链接文件整数比较:-eq -ne -gt-lt-ge-le字符串比较:-z-nstring1 = string2string1 != 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:xxxping -c 2 10.1.1.254 > /dev/null 2>&1if [ $? -eq 0 ];then  echo "$(date '+%F %T')the ip is ok" > /tmp/ip.logelse  echo "$(date '+%F %T')the is is not ok" >> /tmp/ip.logfi或ping -c 2 $1 > /dev/null 2>&1if [ $? -eq 0 ];then  echo "$(date '+%F %T')the ip is ok" > /tmp/ip.logelse  echo "$(date '+%F %T')the is is not ok" >> /tmp/ip.logfiread -p "Input your ip:" IPping -c 2 $IP > /dev/null 2>&1if [ $? -eq 0 ];then  echo "$(date '+%F %T')the ip is ok" > /tmp/ip.logelse  echo "$(date '+%F %T')the is is not ok" >> /tmp/ip.logfi或者read -p "Input your ip:" IPping -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:" IPping -c 2 $IP > /dev/null 2>&1test $? -eq 0 && echo "$(date '+%F %T')the ip is ok" > /tmp/ip.log || echo "$(date '+%F %T')the is is not ok" >> /tmp/ip.logdemo2:判断一个进程是否存在#!/bin/bashps -ef|grep vsftpd|grep -v 'grep' &>/dev/null或者# pgrep -l vsftpd[ $? -eq 0 ] && echo "vsftpd ok" >>/tmp/log ||echo "vsftpd not ok" >>/tmp/logdemo3:判断一个服务是否正常#!/bin/bashwget -P /tmp http://localhost &>/dev/null[ $? -ne 0 ] && echo "httpd not ok" >>/tmp/log ||echo "httpd is ok" >>/tmp/log课堂练习:1、写一个脚本判断一个用户是否存在#!/bin/bashread -p "Input your username:" userid $user &>/dev/nulltest $? -eq 0 && echo user is ok>>/tmp/user.log ||echo user is not ok >>/tmp/user.log2、完善上第一个例子中给脚本传参时的bug,如果每个给脚本传参或者参数个数不等于1时,提示脚本的用法:usage:xxx.sh ipif [ $# -ne 1 ];then    echo "Usage:`basename $0` IP";exitfiping -c 2 $1 > /dev/null 2>&1if [ $? -eq 0 ];then  echo "$(date '+%F %T')the ip is ok" > /tmp/ip.logelse  echo "$(date '+%F %T')the is is not ok" 
0 0
原创粉丝点击