[英]Default values for failed backticks in bash in one command
I am trying to come up with a mechanism to assign a default value to a variable when a command fails. 我试图提出一种在命令失败时为变量分配默认值的机制。 I can't seem to combine them with
||
我似乎无法将它们与
||
结合使用 or inserting $()
inside the 2nd line. 或在第二行中插入
$()
。
How do I convert this to one command? 如何将其转换为一个命令?
MY_COMMAND=$(which somefile)
MY_COMMAND=${MY_COMMAND:-"/usr/local/dev/branch/somefile"}
The following should work in Bash: 以下应在Bash中工作:
MY_VARIABLE="$(which thing || echo 'default')"
As this is using a subshell ( $()
syntax), there should be a complete command on each side of the ||
由于这是使用subshell (
$()
语法)的,因此||
每一侧都应有完整的命令。 or symbol. 或符号。 So the second part should
echo
something. 因此,第二部分应
echo
。
On the opposite, ${}
is used in parameter substitution , and the variable names can't be nested. 相反,
${}
用于参数替换 ,并且变量名称不能嵌套。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.