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

标签 linux bash

我阅读了关于此的 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/

相关文章:

bash - 计划执行返回错误值的 shell 脚本(使用 cron 计划执行脚本)(Ubuntu 20.04.4 LTS)

regex - 如何在 bash 中使用正则表达式运算符 =~ 匹配重复字符?

linux - 如何抑制命令的错误消息?

node.js - centOS无法通过yum安装nodejs

c++ - 使用 g++ 链接对象时出现问题

linux - 我需要加载一些模块,但加载模块在我的环境中不起作用,除非我更改 bash 配置文件。我如何在 tcsh 中执行此操作?

bash - 在 shell 脚本的一行末尾有多余的分号吗?

Bash 等待进程启动

linux - VPS inode 达到限制 - 应删除/删除哪些文件以释放 inode

c - Apache 2.4 MPM worker : Thread Init?