bash 如果字符串中为空,则插入变量值或默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30120079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:57:37  来源:igfitidea点击:

Insert variable value or default value if empty in a string

bashscripting

提问by Heschoon

I want to insert the value of an environment variable in a string or a default value if the corresponding variable is not initialized.

如果相应的变量未初始化,我想在字符串或默认值中插入环境变量的值。

Example:

例子:

if [ -z $MY_VAR ];
then
    MY_VAR="default"
fi

echo "my variable contains $MY_VAR"

I'm however using a lot of variables in my strings and the tests are cluttering my script.

然而,我在我的字符串中使用了很多变量,并且测试使我的脚本变得混乱。

Is there a way to make a ternary expression in my string?

有没有办法在我的字符串中创建三元表达式?

Example of what I want to achieve (it doesn't work):

我想要实现的示例(它不起作用):

echo "my variable contains ${-z $MY_VAR ? $MY_VAR : 'default'}"

回答by chepner

To actually setthe value of the variable, rather than just expanding to a default if it has no value, you can use this idiom:

要实际设置变量的值,而不是仅在没有值时扩展为默认值,您可以使用以下习惯用法:

: ${MY_VAR:=default}

which is equivalent to your original ifstatement. The expansion has the side effect of actually changing the value of MY_VARif it is unset or empty. The :is just the do-nothing command which provides a context where we can use the parameter expansion, which is treated as an argument that :ignores.

这相当于你原来的if陈述。MY_VAR如果未设置或为空,扩展具有实际更改值的副作用。这:只是一个什么都不做的命令,它提供了一个上下文,我们可以在其中使用参数扩展,它被视为:忽略的参数。

回答by Michael Kohl

See Bash Default Values

请参阅Bash 默认值

→ echo "my variable contains ${MY_VAR:-default}"
my variable contains default