开发者社区> 问答> 正文

结合两个否定的文件检查条件(-f和-s)似乎返回错误的结果

我想检查一个文件是否是一个文件并且存在并且是否不为空,所以最终使用了-f和的组合检查-s。如果文件不存在或为空,我想提前返回,所以我同时取消了这两项检查。

为了测试我的文件名返回空字符串并且将路径传递到目录的情况,我尝试这样做:

if [[ ! -f "/path/to/dir/" ]] && [[ ! -s "/path/to/dir/" ]]; 
then  echo "Does not exists"; else echo "Exists"; fi

存在

以上返回“存在”,这似乎是不正确的。

-f 单独检查是否正确:

if [[ ! -f "/path/to/dir/" ]]; then  echo "Does not exists"; 
else echo "Exists"; fi

不存在

合并后的检查但每个检查的结果相同时也是正确的:

if [[ -f "/path/to/dir/" ]] && [[ -s "/path/to/dir/" ]]; 
then  echo "Exists"; else echo "Does not exists"; fi

不存在

不确定将否定条件与逻辑和相结合时,Bash是否做错了&&什么?

编辑1:如建议的那样,尝试使用表示法将两个条件放在同一组括号中:

if [[ ! -f "/opt/gmdemea/smartmap_V2/maps/" && ! -s "/opt/gmdemea/smartmap_V2/maps/" ]]; then  echo "Does not exists"; else echo "Exists"; fi

存在

但这并不能改变行为。

编辑2:从手册页看来,在这种情况下-s应该足够了,但是当传递现有目录路径时,它返回true(Bash版本:4.1.2(1)-release):

if [[ -s "/opt/gmdemea/smartmap_V2/maps/" ]]; then echo "Exists"; else echo "Does not exists"; fi

存在

它不是文件时返回“ Exists”,因此应该转到else子句返回“不存在”

展开
收起
祖安文状元 2020-01-06 15:26:23 324 0
1 条回答
写回答
取消 提交回答
  • 拥有x AND y,然后加以否定,您将得到:NOT (x AND y)。等于(NOT a) OR (NOT b)。这是不是等于(NOT x) AND (NOT y)。

    我想检查一个文件是否是一个文件并且存在并且是否不为空

    如果要检查文件是否为常规文件并且不为空,则可以执行以下操作:

    [[ -f path ]] && [[ -s path ]]
    否定将是(每行相等)(请注意De Morgan定律):
    
    ! ( [[ -f path ]] && [[ -s path ]] )
    [[ ! -f path || ! -s path ]]
    
    

    您也可以这样写(每行相等):

    ! [[ -f path && -s path ]]
    [[ ! ( -f path && -s path ) ]]
    [[ ! -f path ]] || [[ ! -s path ]]
    # or using `[` test and `-a` and `-o`:
    ! [ -f path -a -s path ]
    [ ! -f path -o ! -s path ]
    [ ! \( -f path -a -s path \) ]
    所以就:
    
    
    if [[ ! -f "/path/to/dir/" || ! -s "/path/to/dir/" ]]; then
         echo "The /path/to/dir is not a regular file or size is nonzero"
    else
         echo "The path /path/to/dir is a regular file and it's size is zero"
    fi
    
    2020-01-06 15:26:47
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载