我想检查一个文件是否是一个文件并且存在,如果它不为空,所以最终使用 -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/