Shell常用的逻辑判断


#!/bin/sh   
 myPath="/var/log/httpd/" 
 myFile="/var /log/httpd/access.log" 
  
 #这里的-x 参数判断$myPath是否存在并且是否具有可执行权限 
 if [ ! -x "$myPath"]; then 
  mkdir "$myPath" 
 fi 
  
 #这里的-d 参数判断$myPath是否存在 
 if [ ! -d "$myPath"]; then 
   mkdir "$myPath" 
 fi 
  
 #这里的-f参数判断$myFile是否存在 
 if [ ! -f "$myFile" ]; then 
   touch "$myFile" 
 fi 
  
 #其他参数还有-n,-n是判断一个变量是否是否有值 
 if [ ! -n "$myVar" ]; then 
   echo "$myVar is empty"
   exit 0 
 fi 
  
 #两个变量判断是否相等,在[]中,=号只能对字符起作用
 if [ "$var1" = "$var2" ]; then 
   echo "$var1 eq $var2" 
 else 
   echo "$var1 not eq $var2" 
 fi

shell 编程中经常使用的if语句内判断参数
  –b 当file存在并且是块文件时返回真

  -c 当file存在并且是字符文件时返回真

  -d 当pathname存在并且是一个目录时返回真

  -e 当pathname指定的文件或目录存在时返回真

  -f 当file存在并且是正规文件时返回真

  -g 当由pathname指定的文件或目录存在并且设置了SGID位时返回为真

  -h 当file存在并且是符号链接文件时返回真,该选项在一些老系统上无效

  -k 当由pathname指定的文件或目录存在并且设置了“粘滞”位时返回真

  -p 当file存在并且是命令管道时返回为真

  -r 当由pathname指定的文件或目录存在并且可读时返回为真

  -s 当file存在文件大小大于0时返回真

  -u 当由pathname指定的文件或目录存在并且设置了SUID位时返回真

  -w 当由pathname指定的文件或目录存在并且可执行时返回真。一个目录为了它的内容被访问必然是可执行的。

  -o 当由pathname指定的文件或目录存在并且被子当前进程的有效用户ID所指定的用户拥有时返回真。

  UNIX Shell 里面比较字符写法:    

-eq                    等于                             
-ne 不等于
-gt 大于
-lt 小于
-le 小于等于
-ge 大于等于
-z 空串
= 两个字符相等
!= 两个字符不等
-n 非空串

  • 1
  • 2
  • 下一页

相关内容