Shell总结04-测试和分支

Shell总结04-测试和分支

test条件测试

# “[]”是调用test命令的一种形式

##文件操作
#     [ -e file ] :判断文件是否存在 
#     [ -d dir ]  :判断目录dir是否存在
#     [ -b file ]  :判断块设备是否存在
#     [ -c file ]  :判断字符设备是否存在
#     [ –S File ]  : 套接字文件是否存在
#     [ –r File ]  : 文件是否可读
#     [ –w File ]  : 文件是否可写
#     [ –x File ]  : 文件是否可执行

##数值比较操作
#      [ n1 -eq n2 ]	n1,n2是否相等
#      [ n1 –ne n2 ] n1不等于n2 
#      [ n1 –ge n2 ] n1大于等于n2 
#      [ n1 –gt n2 ] n1大于n2
#      [ $x = $y ] :判断$x和$y是否相等  

#      [ -x /bin/ls ] :判断/bin/ls是否存在并有可执行权限 
#      [ -n $var ] :判断$var变量是否有值 

if then/else(elif))分支

#条件测试通常和if+else/elif+fi代码块儿配合使用,例如
if [ ! -d $NX_LOG ]; then
   mkdir -p $NX_LOG
fi
##磁盘空间检查
## cat disktest.sh
#!/bin/bash
# This script does a very simple test for checking disk space.
space=`df −h | awk '{print $5}' | grep % | grep −v Use | sort −n | tail −1 | cut −d "%"
−f1 −`
alertvalue="80"
if [ "$space" −ge "$alertvalue" ]; then
echo "At least one of my disks is nearly full!" | mail −s "daily diskcheck" root
else
echo "Disk space normal" | mail −s "daily diskcheck" root
fi

case (in) esac分支

case "$variable" in
  "$condition1" )
    command...
  ;;
  "$condition2" )
    command...
  ;;
esac

##系统服务启停命令的实现
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status anacron
        ;;
    restart)
        stop
        start
        ;;
    condrestart)
        if test "x`pidof anacron`" != x; then
            stop
            start
        fi
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart|condrestart|status}"
        exit 1
esac

#对变量进行引用不是必须的,因为在这里不会进行字符分割。
#条件测试语句必须以右括号 ) 结束。
#每一段代码块都必须以双分号 ;; 结束。
#如果测试条件为真,其对应的代码块将被执行,而后整个 case 代码段结束执行。
#case 代码段必须以 esac 结束(倒着拼写case)。
posted @ 2020-06-15 23:14  ElfCafe  阅读(110)  评论(0编辑  收藏  举报