我在bash (3.00) shell脚本中有一大堆关于变量的测试,如果变量没有设置,那么它会分配一个默认值,例如:

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

我似乎记得在一行中做这件事有一些语法,类似于三元运算符,例如:

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

(虽然我知道这行不通……)

是我疯了吗,还是真的有这样的东西存在?


当前回答

回答你的问题和所有变量替换

echo "${var}"
echo "Substitute the value of var."
    

echo "${var:-word}"
echo "If var is null or unset, word is substituted for var. The value of var does not change."
    

echo "${var:=word}"
echo "If var is null or unset, var is set to the value of word."
    

echo "${var:?message}"
echo "If var is null or unset, message is printed to standard error. This checks that variables are set correctly."
    

echo "${var:+word}"
echo "If var is set, word is substituted for var. The value of var does not change."

您可以通过在美元符号和表达式的其余部分之间放置\来转义整个表达式。

echo "$\{var}"

其他回答

对于命令行参数:

VARIABLE="${1:-$DEFAULTVALUE}"

它将传递给脚本的第一个参数的值赋给VARIABLE,如果没有传递这样的参数,则将DEFAULTVALUE的值赋给VARIABLE。引用可以防止词缀和分词。

其实跟你贴出来的很像。您可以使用Bash参数展开来实现这一点。

获取指定的值,如果缺少则默认:

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.

可以像这样链接默认值:

DOCKER_LABEL=${GIT_TAG:-${GIT_COMMIT_AND_DATE:-latest}}

例如,如果$GIT_TAG不存在,则取$GIT_COMMIT_AND_DATE -如果不存在,则取"latest"

回答你的问题和所有变量替换

echo "${var}"
echo "Substitute the value of var."
    

echo "${var:-word}"
echo "If var is null or unset, word is substituted for var. The value of var does not change."
    

echo "${var:=word}"
echo "If var is null or unset, var is set to the value of word."
    

echo "${var:?message}"
echo "If var is null or unset, message is printed to standard error. This checks that variables are set correctly."
    

echo "${var:+word}"
echo "If var is set, word is substituted for var. The value of var does not change."

您可以通过在美元符号和表达式的其余部分之间放置\来转义整个表达式。

echo "$\{var}"

参见这里的3.5.3(shell参数展开)

所以在你的案例中

${VARIABLE:-default}