What is the difference between ${var:-word} and ${var-word}?

陌路散爱 提交于 2019-12-20 05:18:11

问题


I found the following command in a bash script:

git blame $NOT_WHITESPACE --line-porcelain "${2-@}" -- "$file"

What does this ${2-@} mean? Trying out, it returns the 2nd argument, and "@" if it doesn't exist. According to the documentation, ${2:-@} should do the same. I tried it, and it indeed does the same. What's the difference? Where is it documented? The man page does not seem to say anything about this notation.


回答1:


From 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.



来源:https://stackoverflow.com/questions/31136720/what-is-the-difference-between-var-word-and-var-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!