Reputation: 11730
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.
Upvotes: 1
Views: 460
Reputation: 290415
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.
Upvotes: 8