Testing User Input Arguments to a Bash Function

I am handling the parsing of bash function arguments in the following way. The function affirm-numeric -W "$arg" tests if arg is a whole number (0,1,2,...), returning a value greater than zero, when arg is confirmed to be a whole number.

There are two possibilities to test the user inputs. As I do here, for each option. Otherwise make the checks after parsing the values through the while loop.

I wonder which would be the better approach in terms of functionality. It seems to me that the way I am doing it gives me more flexibility upon the parsing procedure.

  while (( $# > 0 )); do
    case $1 in
     ("-T"|"--tail")               # -T 21
          nchk=$( affirm-numeric -W "$2" )
         if (( nchk > 0 )); then
           tm="$2" ; shift ; shift
         else
           err+=(": -T failed numeric validation")
         fi 
         ;;
     ("-T="*|"--tail="*)           # -T=21
         nchk=$( affirm-numeric -W "${1#*=}" )
         if (( nchk > 0 )); then
           tm="${1#*=}" ; shift
         else
           err+=(": -T failed numeric validation")
         fi
         ;;
     ("-T"*)                       # -T21
         nchk=$( affirm-numeric -W "${1#-T}" )
         if (( nchk > 0 )); then
           tm="${1#*T}" ; shift
         else
           err+=(": -T failed numeric validation")
         fi
         ;;
     ("--") shift ; break ;;
     ("-"*) err=( "?" ) ; shift ;;
     (*) break ;;
    esac
  done
2
Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article