代码之家  ›  专栏  ›  技术社区  ›  Casebash

Bash参数替换中:-和:=之间的区别是什么?

  •  14
  • Casebash  · 技术社区  · 8 年前

    Bash参数替换中:-和:=之间的区别是什么?

    他们似乎都设置了默认值?

    3 回复  |  直到 7 年前
        1
  •  14
  •   PesaThe    8 年前

    引用 Bash Reference Manual :

    ${parameter:-word}

    如果 parameter 是unset或null,则扩展为 word 已替换。否则 参数 已替换。

    ${parameter:=word}

    如果 参数 是unset或null,则扩展为 单词 已分配给 参数 . 的价值 参数 那么 已替换。位置参数和特殊参数不能 以这种方式分配给。

    区别在于 := 不只是代替 单词 ,它也 分配 将其发送到 参数 :

    var=
    echo "$var"               # prints nothing
    echo "${var:-foo}"        # prints "foo"
    echo "$var"               # $var is still empty, prints nothing
    echo "${var:=foo}"        # prints "foo", assigns "foo" to $var
    echo "$var"               # prints "foo"
    

    看到了吗?太好了 wiki.bash-hackers.org tutorial 了解更多信息。

        2
  •  2
  •   KamilCuk    8 年前

    从…起 https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html :

    ${parameter:-word}
    If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
    
    ${parameter:=word}
    If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.
    

    In:-不修改参数值,只“打印”word的展开。In:=该参数获取新值,该值是word的扩展,并且它还“打印”word的扩展。
    有时,在脚本中,如果变量未设置,则需要为其指定默认值。多用途 VAR=${VAR:-1} ,如果未设置VAR,则会将“1”分配给VAR。这也可以写为 : ${VAR:=1} ,如果未设置并运行VAR,则会将“1”分配给VAR : $VAR : 1 但是 : 是bash中的一个特殊内置项,将放弃所有参数而不执行任何操作。

        3
  •  2
  •   iamauser    8 年前
    $ var=
    $ echo $(( ${var:-1} + 3 ))  # local substitution if value is null
    4
    $ echo $(( ${var} + 3 ))
    3
    
    # set it to null 
    $ var= 
    $ echo $(( ${var:=1} + 3 )) # global substitution if value is null
    4
    $ echo $(( ${var} + 3 ))
    4 
    

    https://www.tldp.org/LDP/abs/html/parameter-substitution.html

    推荐文章