我在bash (3.00) shell脚本中有一大堆关于变量的测试,如果变量没有设置,那么它会分配一个默认值,例如:
if [ -z "${VARIABLE}" ]; then
FOO='default'
else
FOO=${VARIABLE}
fi
我似乎记得在一行中做这件事有一些语法,类似于三元运算符,例如:
FOO=${ ${VARIABLE} : 'default' }
(虽然我知道这行不通……)
是我疯了吗,还是真的有这样的东西存在?
我在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}"
其他回答
其实跟你贴出来的很像。您可以使用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.
还有一种更简洁地表达“if”结构的方法:
FOO='default'
[ -n "${VARIABLE}" ] && FOO=${VARIABLE}
对于命令行参数:
VARIABLE="${1:-$DEFAULTVALUE}"
它将传递给脚本的第一个参数的值赋给VARIABLE,如果没有传递这样的参数,则将DEFAULTVALUE的值赋给VARIABLE。引用可以防止词缀和分词。
回答你的问题和所有变量替换
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}"
你甚至可以使用其他变量的默认值
有一个文件defvalue.sh
#!/bin/bash
variable1=$1
variable2=${2:-$variable1}
echo $variable1
echo $variable2
执行./ value.sh first-value - second-value output
first-value
second-value
执行./ value.sh first-value output
first-value
first-value