Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 如果文件名为空,为什么[-f file\u name]或[-e file\u name]返回True?_Linux_Bash_Shell - Fatal编程技术网

Linux 如果文件名为空,为什么[-f file\u name]或[-e file\u name]返回True?

Linux 如果文件名为空,为什么[-f file\u name]或[-e file\u name]返回True?,linux,bash,shell,Linux,Bash,Shell,我知道[-f file],如果我们使用它作为条件检查,检查文件是否是普通文件,而不是目录或特殊文件;如果是,则条件变为真。 我还知道[-e file]检查文件是否存在;即使文件是目录,也为true 假设我有如下代码(另存为test.sh),用于检查它是否为常规文件: #!/bin/bash file=$1 if [ -e $file ] then echo "file exists" if [ -f $file ]

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

假设我有如下代码(另存为
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 /etc/passwd
    file exists
    Its a regular file
如果我将无效文件或目录作为参数传递:

    ./test.sh dsdsafds
但输出仍如预期:

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

如果条件得到满足,我的输出为:

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

如果我可以输出/打印这些测试操作符返回的布尔值,有什么方法吗

  • 因为
    [-f$file]
    $file
    为空时变为
    [-f]
    ,所以表达式始终为真,因为
    -f
    不是空字符串。从
    manbash

    test
    [
    使用一组基于参数数量的规则计算条件表达式

    0个参数
    这个表达是错误的

    1个参数
    当且仅当参数不为null时,表达式才为真。

    2个参数
    如果第一个参数是
    ,则当且仅当第二个参数为空时,表达式才为真。如果第一个参数是上面条件表达式下列出的一元条件运算符之一,则如果一元测试为真,则表达式为真。如果第一个参数不是有效的一元条件运算符,这个表达是错误的

    因此,引用变量
    file
    可以防止您面临的错误(例如
    [-f“$file”]

  • […]和&echo true | | echo false


  • 您必须使用if[…].然后呢works@AndreGelinas这也很好。谢谢你的回复。我没有首先注意到你的回复。它起作用了,我理解了原因。谢谢你的快速回复:)如果这个答案引用或解释了这种不直观的语法是如何产生的或为什么产生的,那会更好。或者这可能是另一个问题…@oguzismail,很抱歉编辑失败了t令人不满意。在上一次修订版中,是否有理由不引用
    info test
    作为引用的来源?我建议强调引用可以防止错误,而不是告诉人们引用,而是将其作为一种预防措施隐式保留。@agc,这是未引用的扩展经过strin的自然结果g-spliting和globbing;没有人做出明确的设计决策,认为
    test
    会使用这种语法——相反,它与上世纪70年代的所有其他常规命令具有相同的扩展规则。。