gpt4 book ai didi

linux - "var=${var:-word}"和 "var=${var:=word}"有什么区别?

转载 作者:IT王子 更新时间:2023-10-29 00:24:24 28 4
gpt4 key购买 nike

我阅读了关于此的 bash 手册页,但我不明白其中的区别。我对它们进行了测试,它们似乎产生了完全相同的结果。

如果值不是通过命令行参数设置的,我想设置一个变量的默认值。

#!/bin/bash

var="$1"
var=${var:-word}
echo "$var"

如果 $1 为 null,上面的代码将回显 word,如果不为 null,则回显 $1 的值。这样做也是如此:

#!/bin/bash

var="$1"
var=${var:=word}
echo "$var"

根据 Bash 手册页,

${parameter:-word} Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

${parameter:=word} Assign Default Values. 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.

是不是它们是一样的,只是${parameter:=word}做的更多?

最佳答案

因为您使用了两次 var,所以您看不到示例的区别,但是您可以通过两个不同的变量看到它:

foo=${bar:-something}

echo $foo # something
echo $bar # no assignement to bar, bar is still empty

foo=${bar:=something}

echo $foo # something
echo $bar # something too, as there's an assignement to bar

关于linux - "var=${var:-word}"和 "var=${var:=word}"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17404696/

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