代码之家  ›  专栏  ›  技术社区  ›  James Wright user3667089

字符串同时大于零和空

  •  2
  • James Wright user3667089  · 技术社区  · 6 年前

    有人能解释一下这到底是怎么回事吗?

    的内容 insanity.sh :

    #!/bin/bash
    
    ARG=""
    
    if [ -n $ARG ]; then
        echo string is greater than zero
    fi
    
    if [ -z $ARG ]; then
        echo string is empty
    fi
    

    运行脚本:

    [USERNAME@login001 clusterUtils]$ ./insanity.sh
    string is greater than zero
    string is empty
    

    当前正在使用 this 目前的教程。

    1 回复  |  直到 6 年前
        1
  •  4
  •   anubhava    6 年前

    这是因为你没有报价 $ARG 里面 [ ... ]

    不引用代码就是 有效地 运行方式:

    if [ -n ]; then
        echo string is greater than zero
    fi
    
    if [ -z ]; then
        echo string is empty
    fi
    

    之间的任何非空字符串 …] 将计算为真 ,因此两者都是 if 条件是成功的。


    修复: 建议使用 [[ ... ]] 当你使用 bash :

    arg=""
    
    if [[ -n $arg ]]; then
        echo 'string is greater than zero'
    fi
    
    if [[ -z $arg ]]; then
        echo 'string is equal to zero, empty'
    fi
    

    [……] 不需要像这样引用变量 …] 正弦 [ 是外部命令,并且 [……] ] 是一个内置的bash构造。

    还要避免脚本中的所有大写变量,以避免与保留的env变量冲突。