代码之家  ›  专栏  ›  技术社区  ›  Jesper.Lindberg

检查参数是否包含null

  •  0
  • Jesper.Lindberg  · 技术社区  · 10 月前

    我想看看shell脚本的输入参数是否包含null。

    我有以下脚本( test-print-null.sh ):

    #!/bin/sh                                                                                                                                                                                                                                                                             
    printf "All params: $@\n"
    printf "Value at pos 0: $0\n"
    printf "Value at pos 1: $1\n"
    printf "Value at pos 2: $2\n"
    [[ -z "$1" ]] && printf "Pos 1 is null\n"
    [[ -z "$2" ]] && printf "Pos 2 is null\n"
    
    for var in "$@"
    do
        ${var:+false} [ -n "${var+1}" ] && printf "Params is null!\n" && for param in "$@"; do printf "Params: %s \n" "$param" ; done;
    done;
    

    然后我运行脚本 ./test-print-null.sh "hello" "" 这告诉我pos2是空的。但是,我想在字符串hello中嵌入一个空字符并检查一下。我试过了 ./test-print-null.sh "hel\0lo" "" 这并不像预期的那样工作。

    1 回复  |  直到 10 月前
        1
  •  1
  •   KamilCuk    10 月前

    我想在字符串hello中嵌入一个空字符

    不可能在字符串中嵌入空字符。在shell中,字符串以零字节结尾。

    变量可以不设置或设置。如果设置,变量可以为空或不为空。 [[ -z 检查字符串是否为空( -z 比如“零”)。

    shell脚本包含null。

    无法检查变量或参数在shell中是否包含零字节。

    这告诉我pos2是空的。

    第二个位置参数是空字符串,是的。