gpt4 book ai didi

linux - 如果 file_name 为空,为什么 [ -f file_name] 或 [ -e file_name ] 返回 True?

转载 作者:太空狗 更新时间:2023-10-29 11:40:38 25 4
gpt4 key购买 nike

<分区>

我知道 [ -f file ],如果我们将它用作条件检查,检查 file 是否是普通文件而不是目录或特殊文件;如果是,则条件变为真。我也知道 [ -e file ] 检查 file 是否存在;即使 file 是一个目录也是如此。

假设我有一些代码如下(保存为 test.sh)用于检查它是否是常规文件:

    #!/bin/bash 

file=$1
if [ -e $file ]
then
echo "file exists"
if [ -f $file ]
then
echo "It's a regular file"
else
echo "It's not a regular file"
fi
else
echo "file doesn't exist"
fi

我正在运行如下:

    ./test.sh /etc/passwd

我的输出如下所示:

    file exists
Its a regular file

如果我传递一个无效的文件或目录作为参数:

    ./test.sh dsdsafds

输出仍然符合预期:

    file doesn't exist

但是如果我在没有任何参数的情况下运行脚本,(意味着 $1 将为空):

    ./test.sh

两个 if 条件都得到满足,我的输出是:

    file exists
Its a regular file

为什么会这样?即使 $1 为空,[ -e file ][ -f file ] 怎么可能为真?

有什么方法可以输出/打印此类测试运算符返回的 bool 值吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com