Idiomatic way to test if no positional params are given?

后端 未结 5 822
暖寄归人
暖寄归人 2021-01-13 10:03

What is the most idiomatic way in Bash to test if no positional parameters are given? There are so many ways to check this, I wonder if there is one preferred way.

S

5条回答
  •  情话喂你
    2021-01-13 10:33

    Use Sensible Semantics

    The key is readability and the intent of your code. Unless you have a good reason to do otherwise, you probably just want to determine the length of the parameter list.

    # Is length of parameter list equal to zero?
    [ $# -eq 0 ]
    

    However, you can certainly use any parameter expansion or comparison operator that expresses the intent of your code. There's no right way to do it, but you certainly may wish to consider whether the semantics of your test are portable.

    Food for Thought

    It isn't the conditional expression that's intrinsically important. What's important is why you want to know. For example:

    set -e
    foo="$1"
    shift
    
    # $2 is now $1 (but only if the line is reached)
    echo "$1"
    

    In this case, the length of the parameter list is never checked directly. The first parameter is simply assigned (even though it may be unset), and then the shell throws an error and exits when you try to shift the parameter list. This code says "I just expect the parameters to be there; I shouldn't have to check for them explicitly."

    The point here is that you need to determine what your code is trying to express, and match the semantics of your tests and conditionals to express that as clearly as you can. There really is no orthogonal answer.

提交回复
热议问题