Idiomatic way to test if no positional params are given?

后端 未结 5 866
暖寄归人
暖寄归人 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:36

    Here's a most logical way:

    [ ! $@ ]
    

    It is based on a single rule:

    [ ] # this returns 1
    

    Well then,

    [ ! ] # this returns 0
    

    The rest is obvious: $@ is the special parameter that expands to a list of all positional parameters.

    Test: (It will work even if you throw a couple of empty strings ("" "" "") at it.)

    if [ ! $@ ]; then
        printf 'Note: No arguments are given.'
    fi
    

提交回复
热议问题