bash参数扩展$ {parameter:-SUB}与$ {parameter-SUB} [英] bash parameter expansion ${parameter:-SUB} vs ${parameter-SUB}

查看:47
本文介绍了bash参数扩展$ {parameter:-SUB}与$ {parameter-SUB}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一些bash脚本(在GNU bash版本3.2.51(1)上)带有参数替换,例如

I see some bash scripts (on GNU bash, version 3.2.51(1)) with a parameter substitution like

function foo() {
  local x=${1-XYZ} ##### (1) 
  echo "x=${x}."
}
foo ####### this prints x=XYZ
foo ABCD ###### this prints x=ABCD

更常见的是,我在(1) x = $ {1:-XYZ} 上看到了该代码,我也可以在Bash参考页

More commonly I see at (1) x=${1:-XYZ} and I can find it also described in the Bash reference pages here. Are both correct, or is something else also happening in the background and it might fail in some circumstances?

它不必是 $ 1 -只要未定义 $ {XX-sub} 中的变量,它就会选择替代项.非常感谢

It does not have to be $1 - so long as the variable in ${XX-sub} is not defined, it picks the substitute. Thanks a lot

推荐答案

如果未设置 value ,请使用 default ,否则,请使用 value :

If value is not set, use default, otherwise, use value:

var=${value-$default}
var=${value:-$default}   # ':' use default even if value declared and empty/null

例如(缺少命令行参数):

e.g (missing command line parameters):

value=
var=${value-$default}     # not set
var=${value:-$default}    # set to $default

这篇关于bash参数扩展$ {parameter:-SUB}与$ {parameter-SUB}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆