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

本文总结了BASH命令和SHELL脚本中的判断技巧,包括使用$(( ))进行数值比较,如<、>、<=、>=、==、!=,以及利用条件语句测试文件属性,如-e、-s、-r、-w、-x、-o、-f、-d等。还介绍了如何检查文件夹是否存在、变量长度以及目录的可执行权限。同时,文章提供了不同方法测试变量长度,包括wc -c、expr length和awk命令,并展示了if条件判断的结构和用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值