An idiomatic way to check for positional parameters?

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

Some ways:

((! $# )) # check if $# is 'not true' (($# == 0)) # $# is 0 [[ ! $@ ]] # $@ is unset or null 
+3
source share
5 answers

For me, the classic way:

 [[ $# -eq 0 ]] 
+3
source

If you want the error to not have positional parameters:

 : ${@?no positional parameters} 

will output โ€œno positional parametersโ€ to a standard error (and exit the non-interactive shell) if $@ not set.

Otherwise, I do not know the best options, except for one of the various verification methods, if $# is 0.

+1
source

Use smart semantics

The key is the readability and intent of your code. If you have no reason for this, 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 use any extension or parameter comparison operator that expresses the intent of your code. There is no right way to do this, but you can of course think about the portability of the semantics of your test.

Food for thought

This is not a conditional expression, which is inherently important. What is important, why you want to know. For instance:

 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 if it can be canceled), and then the shell throws an error and exits when you try to move the parameter list. This code says: "I just expect the parameters to be there, I would not have to check them explicitly."

The point is that you need to determine what your code is trying to express and match the semantics of your tests and conventions to express it as clearly as you can. There is actually no orthogonal answer.

+1
source

Here is the most logical way:

 [ ! $@ ] 

It is based on one rule:

 [ ] # this returns 1 

Well then

 [ ! ] # this returns 0 

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

Test: (It will work even if you press a couple of blank lines ("" "" ") on it.)

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

I prefer to use the fact that if there are no positional parameters, then there is also no first parameter:

 [[ -z $1 ]] test -z "$1" [ -z "$1" ] 

This is just a little easier for the reader. Of course, this only works if the assumption that the first parameter cannot be an empty string is true.

-2
source

Source: https://habr.com/ru/post/1208940/


All Articles