What is the meaning of a question mark in bash variable parameter expansion as in ${var?}?

后端 未结 4 1878
花落未央
花落未央 2020-12-08 06:46

What is the meaning of a bash variable used like this:

 ${Server?}
4条回答
  •  攒了一身酷
    2020-12-08 06:57

    It works almost the same as (from the bash manpage):

    ${parameter:?word}
    Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

    That particular variant checks to ensure the variable exists (is both defined and not null). If so, it uses it. If not, it outputs the error message specified by word (or a suitable one if there is no word) and terminates the script.

    The actual difference between that and the non-colon version can be found in the bash manpage above the section quoted:

    When not performing substring expansion, using the forms documented below, bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is unset.

    In other words, the section above can be modified to read (basically taking out the "null" bits):

    ${parameter?word}
    Display Error if Unset. If parameter is unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

    The difference is illustrated thus:

    pax> unset xyzzy ; export plugh=
    
    pax> echo ${xyzzy:?no}
    bash: xyzzy: no
    
    pax> echo ${plugh:?no}
    bash: plugh: no
    
    pax> echo ${xyzzy?no}
    bash: xyzzy: no
    
    pax> echo ${plugh?no}
    
    pax> _
    

    There, you can see that while both unset and null variable result in an error with :?, only the unset one errors with ?.

提交回复
热议问题