linux - 组合两个否定的文件检查条件(-f 和 -s)似乎返回不正确的结果

标签 linux bash

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

为了测试我的文件名返回空字符串并且我正在传递目录路径的场景,我正在尝试这样做:

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

Exists

上面返回的“存在”似乎不正确。

-f 单独检查是否正确:

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

Does not exists

组合检查但不否定每个检查也是正确的:

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

Does not exists

不确定在将否定条件与逻辑和 && 组合时,我是否做错了什么或者 Bash 中是否存在一些奇怪的地方?

编辑 1: 正如所建议的那样,尝试使用两个条件都在同一组括号中的符号:

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

Exists

但这不会改变行为。

编辑 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 子句返回“不存在”

最佳答案

x AND y,然后对其进行 nagating 得到:NOT (x AND y)。这等于 (NOT a) OR (NOT b)。它等于(NOT x) AND (NOT y)

I want to check if a file is a file and exists and if it is not empty

如果你想检查一个文件是否是一个普通文件,如果它不为空,那么你可以这样做:

[[ -f path ]] && [[ -s path ]]

否定将是(每行相等)(注意 De Morgan's law ):

! ( [[ -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

关于linux - 组合两个否定的文件检查条件(-f 和 -s)似乎返回不正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56870982/

相关文章:

linux - 正确设置环境变量

c++ - 使用 Code::Blocks GNU 编译器编译多线程代码

python - 如何将 python 变量传递到 bash 脚本函数中

Bash curl 和 url 中间的变量

bash - 在 bash 中将变量扩展为 "${var%%r*}"是什么意思?

regex - Linux - 在路径中的每个斜杠后查找与正则表达式匹配的结果

c++ - 如何在 C++/Linux 中创建目录树?

c - 使用原子和 futexes 锁定代码时无法找到竞争条件

BASH:在文件中搜索几个关键字并突出显示它们

linux - 在远程计算机上运行脚本时如何在我的计算机上发出 "beep"?