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

前端 未结 1 777
南笙
南笙 2021-01-24 06:43

I found the following command in a bash script:

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

What does this ${2-@}<

相关标签:
1条回答
  • 2021-01-24 07:29

    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.

    0 讨论(0)
提交回复
热议问题