Test for a Bash variable being unset, using a function

后端 未结 7 1308
逝去的感伤
逝去的感伤 2020-12-07 11:37

A simple Bash variable test goes:

${varName:?    \"${varName} is not defined\"}

I\'d like to re-use this, by putting it in a function. How

7条回答
  •  爱一瞬间的悲伤
    2020-12-07 12:06

    I don't have understood exactly what do you need. I'm trying to replying you despite of this.

    I.e. I need to exit if the test fails.

    The code:

    ${varName:?    "${varName} is not defined"}
    

    will return a non zero exit code when there is not a variable named "varName". The exit code of the last command is saved in $?.

    About your code:

    val=${1:?    "${1}    must be defined, preferably in $basedir"}
    

    Maybe it is not doing what you need. In the case that $1 is not defined the "${1}" will be substituted with nothing. Probably you want use the single quotes that literally writes ${1} without substitution.

    val=${1:?    '${1}    must be defined, preferably in $basedir'
    

提交回复
热议问题