${var:-word} 和 ${var-word} 有什么区别?
What is the difference between ${var:-word} and ${var-word}?
我在 bash 脚本中找到以下命令:
git blame $NOT_WHITESPACE --line-porcelain "${2-@}" -- "$file"
这个${2-@}
是什么意思?尝试一下,它 returns 第二个参数,如果不存在则为“@”。 According to the documentation、${2:-@}
也应该这样做。我试过了,确实是一样的。有什么不同?它在哪里记录?手册页似乎没有说明任何有关此表示法的内容。
来自Bash hackers wiki - parameter expansion:
${PARAMETER:-WORD}
${PARAMETER-WORD}
If the parameter PARAMETER is unset (never was defined) or null
(empty), this one expands to WORD, otherwise it expands to the value
of PARAMETER, as if it just was ${PARAMETER}. If you omit the :
(colon), like shown in the second form, the default value is only used
when the parameter was unset, not when it was empty.
echo "Your home directory is: ${HOME:-/home/$USER}."
echo "${HOME:-/home/$USER} will be used to store your personal data."
If HOME is unset or empty, everytime you want to print something
useful, you need to put that parameter syntax in.
#!/bin/bash
read -p "Enter your gender (just press ENTER to not tell us): " GENDER
echo "Your gender is ${GENDER:-a secret}."
It will print "Your gender is a secret." when you don't enter the
gender. Note that the default value is used on expansion time, it is
not assigned to the parameter.
我在 bash 脚本中找到以下命令:
git blame $NOT_WHITESPACE --line-porcelain "${2-@}" -- "$file"
这个${2-@}
是什么意思?尝试一下,它 returns 第二个参数,如果不存在则为“@”。 According to the documentation、${2:-@}
也应该这样做。我试过了,确实是一样的。有什么不同?它在哪里记录?手册页似乎没有说明任何有关此表示法的内容。
来自Bash hackers wiki - parameter expansion:
${PARAMETER:-WORD}
${PARAMETER-WORD}
If the parameter PARAMETER is unset (never was defined) or null (empty), this one expands to WORD, otherwise it expands to the value of PARAMETER, as if it just was ${PARAMETER}. If you omit the : (colon), like shown in the second form, the default value is only used when the parameter was unset, not when it was empty.
echo "Your home directory is: ${HOME:-/home/$USER}." echo "${HOME:-/home/$USER} will be used to store your personal data."
If HOME is unset or empty, everytime you want to print something useful, you need to put that parameter syntax in.
#!/bin/bash read -p "Enter your gender (just press ENTER to not tell us): " GENDER echo "Your gender is ${GENDER:-a secret}."
It will print "Your gender is a secret." when you don't enter the gender. Note that the default value is used on expansion time, it is not assigned to the parameter.