在 bash 中使用单个命令为 shell 变量分配默认值 [英] Assigning default values to shell variables with a single command in bash

查看:24
本文介绍了在 bash 中使用单个命令为 shell 变量分配默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 bash (3.00) shell 脚本中的变量进行了大量测试,如果未设置变量,则它会分配一个默认值,例如:

I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.:

if [ -z "${VARIABLE}" ]; then 
    FOO='default'
else 
    FOO=${VARIABLE}
fi

我似乎记得有一些语法可以在一行中执行此操作,类似于三元运算符,例如:

I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.:

FOO=${ ${VARIABLE} : 'default' }

(虽然我知道那行不通...)

(though I know that won't work...)

我疯了,还是存在类似的东西?

Am I crazy, or does something like that exist?

推荐答案

实际上非常接近您发布的内容.您可以使用名为 Bash 参数扩展 的东西完成这个.

Very close to what you posted, actually. You can use something called Bash parameter expansion to accomplish this.

获取指定的值,或者 default 如果它丢失:

To get the assigned value, or default if it's missing:

FOO="${VARIABLE:-default}"  # If variable not set or null, use default.
# If VARIABLE was unset or null, it still is after this (no assignment done).

或者同时将default赋值给VARIABLE:

FOO="${VARIABLE:=default}"  # If variable not set or null, set it to default.

这篇关于在 bash 中使用单个命令为 shell 变量分配默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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