linux - 如何理解 ${var :-world}

标签 linux shell

<分区>

# echo ${var}

# echo ${var:-world}
world
# var='hello'
# echo ${var}
hello
# echo ${var:-world}
hello

你能解释为什么第二个 echo ${var:-world} 输出 hello 而不是 world 吗?

对了,topic用英文叫什么?我搜索了 cut string,sub string ... 谢谢。

最佳答案

${name:-alternate} 是一个具有默认值的参数扩展。来自man page :

${parameter:-word}

Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

第一个 ${var:-world} 打印了 world 因为 $var 没有设置。第二个输出 hello 因为你已经设置了 $var=hello,所以 $var 不再被取消设置。因此,默认值 (world) 被忽略了。

更多信息在bash-hackers wiki .

关于linux - 如何理解 ${var :-world},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43679975/

相关文章:

regex - 返回结果的一部分 (GREP)

linux - 重新启动后过时的 PID 文件

php ffmpeg 获取视频时长

c - 如何检测用户输入是 while 循环中的 [ Control ] + [ D ]

linux - bash 合并文件中的行

linux - Ubuntu 中的 Haskell

linux - 802.11 Sniffer 捕获分析 deauth 数据包与 wireshark

linux - 从 SD 卡启动 linux

xml - Bash 脚本 : Get XML elements into array using xmllint

java - 如何从java命令行linux运行 "npm run android"