关于shell-script:shell-ifelsefi

15次阅读

共计 1547 个字符,预计需要花费 4 分钟才能阅读完成。

文件表达式

-e filename 如果 filename 存在,则为真
-d filename 如果 filename 为目录,则为真 
-f filename 如果 filename 为惯例文件,则为真
-L filename 如果 filename 为符号链接,则为真
-r filename 如果 filename 可读,则为真 
-w filename 如果 filename 可写,则为真 
-x filename 如果 filename 可执行,则为真
-s filename 如果文件长度不为 0,则为真
-h filename 如果文件是软链接,则为真
filename1 -nt filename2 如果 filename1 比 filename2 新,则为真。filename1 -ot filename2 如果 filename1 比 filename2 旧,则为真。

整数变量表达式

-eq 等于
-ne 不等于
-gt 大于
-ge 大于等于
-lt 小于
-le 小于等于 

字符串变量表达式

If  [$a = $b]                 如果 string1 等于 string2,则为真
                                字符串容许应用赋值号做等号
if  [$string1 !=  $string2]   如果 string1 不等于 string2,则为真       
if  [-n $string]             如果 string 非空 (非 0),返回 0(true)  
if  [-z $string]             如果 string 为空,则为真
if  [$sting]                  如果 string 非空,返回 0 (和 - n 相似) 

逻辑非 ! , 条件表达式的相同

if [! 表达式]
if [! -d $num]               如果不存在目录 $num

逻辑与 –a , 条件表达式的并列

if [表达式 1  –a  表达式 2]

逻辑或 -o , 条件表达式的或

if [表达式 1  –o 表达式 2]

if-then-fi 语句能够用来判断根本的单层的分支构造

#! /bin/sh
#应用条件测试判断 /bin/bash 是否是一个惯例文件
if [-f /bin/bash]; then 
    echo "/bin/bash is a file"
fi

if-then-else-fi 语句能够解决两层的分支判断语句

#! /bin/sh
#输入提示信息
echo "Please enter a number:"
#从键盘读取用户输出的数字
read num
#如果用户输出的数字大于 10
if ["$num" -gt 10]; then
        #输入大于 10 的提示信息
     echo "The number is greater than 10."
#否则
else
    #输入小于或者等于 10 的提示信息
        echo "The number is equal to or less than 10."
fi

if-then-elif-then-elif-then-…-else-fi。这种语句能够实现多重判断,留神最初肯定要以一个 else 结尾

#! /bin/sh
echo "Please enter a score:"

read score

if [-z "$score"]; then
   echo "You enter nothing.Please enter a score:"
   read score
else
   if ["$score" -lt 0 -o "$score" -gt 100]; then
      echo "The score should be between 0 and 100.Please enter again:"
      read score
   else
      #如果问题大于 90
      if ["$score" -ge 90]; then
         echo "The grade is A."
      #如果问题大于 80 且小于 90
      elif ["$score" -ge 80]; then
         echo "The grade is B."
      #如果问题大于 70 且小于 80
      elif ["$score" -ge 70]; then
         echo "The grade is C."
      #如果问题大于 60 且小于 70
      elif ["$score" -ge 60]; then
         echo "The grade is D."
      #如果问题小于 60
      else
         echo "The grade is E."
      fi
   fi
fi
正文完
 0