'How to handle Error "shift count must be <= $#" in Zsh?

I want to build a command args like this:

$ command <args> <parameter>

$ cut -d ' '

The code to build the command is written like this:

function command(){
  if [ "$#" -gt 0 ]; then
    while [ "$#" -gt 0 ]; do
      case "$1" in
        '-t'|'--type')
          type_parameter=$2
          shift 2
        ;;
        * )
          shift 1
        ;;
      esac
    done
  fi
}

And I want to detect that if after special <args> do not have any parameter exist, then I can write an error handler code.

$ command -t 123 # this is the input value I want.
good input!!

$ command -t     # I want to detect this situation happen.
wrong input!!

But now I meet the error:

$ command -t 
command:shift:101: shift count must be <= $#

I have no idea how to solve this, is there has any way to handle or avoid it perfectly?



Solution 1:[1]

Simply by testing the number of parameters. Instead of doing a shift 2 unconditionally, you can do something like

 if (( $# >= 2 ))
 then
   shift 2
 else
   echo "You need to provide an argument to -z!"
   exit 21
 fi

This would allow you to print your own error message. Of course, if you don't want to treat the missing option argument as an error, you can also break out from the loop (since you know that there won't be any arguments left anyway).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user1934428