BASH命令和SHELL脚本总结(7)判断篇

来源:互联网 发布:怎么预测时间序列数据 编辑:程序博客网 时间:2024/06/05 04:31

@$(( ))用在测试判断中@

a=5;b=7;echo$((a<b))

输出结果为1

类似的判断语句有

<:小于

>:大于

<=:小于或等于

>=:大于或等于

==:等于

!=:不等于

 

@使用条件语句来判断文件属性@

可以用man test看到更多详细情况

格式:-操作符 filename  

-e 文件存在返回1, 否则返回0  

-s 文件大小不为零返回1, 否则返回0  

-r 文件可读返回1,否则返回0  

-w 文件可写返回1,否则返回0  

-x 文件可执行返回1,否则返回0  

-o 文件属于用户本人返回1, 否则返回0  

-f 文件为普通文件返回1, 否则返回0  

-d 文件为目录文件时返回1, 否则返回0  

operator producestrue if... number of operands

-n operand nonzero length 

-z operand haszero length 

-d there exists adirectory whose name is operand 

-f there exists afile whose name is operand 

-eq the operandsare integers and they are equal 

-neq the oppositeof -eq 

= the operandsare equal (as strings) 

!= opposite of= 

-lt operand1 isstrictly less than operand2 (both operands should be integers) 

-gt operand1 isstrictly greater than operand2 (both operands should be integers) 

-ge operand1 isgreater than or equal to operand2 (both operands should be integers) 

-le operand1 isless than or equal to operand2 (both operands should be integers) 

 

例1 .  测试一个文件夹是否存在

MyDir="/search/feiwenyi/"

if [  -d  "$MyDir" ]

then

  echo"the dir $MyDir exists"

else

  echo"the dir $MyDir  does not exist"

Fi

 

例2. 测试变量的长度

MyVar=""

if [ -z"$MyVar"]

then

  echo"The variable has zero length"

else

  echo"The variable has non zero length"

fi

 

例3.目录是否存在或者具有权限  

#!/bin/sh  

myPath="/var/log/httpd/" 

myFile="/var/log/httpd/access.log"  

 

这里的-x 参数判断$myPath是否存在并且是否具有可执行权限  

if [ ! -x"$myPath"]; then  

mkdir"$myPath"  

fi  

 

这里的-f参数判断$myFile是否存在  

if [ ! -f"$myFile" ]; then  

touch"$myFile"  

fi   

 

@测试变量的长度@

方法一

[@djt_8_178CodeRun]# echo "$a"|wc -c                        #可能是考虑了字符串结束符,计算结果为实际长度+1

6

方法二 expr

[@djt_8_178CodeRun]# a=apple

[@djt_8_178CodeRun]# echo `expr length "$a"`            #计算结果为实际长度

5

方法三 awk

str=apple

echo"$str"|awk '{print length($0)}'

5


 @if条件判断@

if [ 条件判断一 ] && (||) [ 条件判断二 ]
then
    执行第一段程序
elif [ 条件判断三 ] && (||) [ 条件判断四 ]
then
    执行第二段程序
else
    执行第三段內容
fi

原创粉丝点击