Search code examples
linuxbashshellcentosgetopts

How to echo when there is no input in getopts command


This is put before the case statements. It still outputs nothing when executed without any input.

 while getopts :x:y:z: OPT; do
 if [ $OPT == "" ]; then
 echo "Null"
 exit 10
 fi

also, how should I code this to execute the values in any position/order? such as:

 .\project -x 120 -y 170 -z Car
 .\project -y 170 -z Car -x 120

Solution

  • You can first test if no arguments were passed at all and exit (this happens before the getopts loop):

    if [ $# -eq 0 ]; then
      usage # Call usage function or echo some usage message
      exit 
    fi
    

    There's no way of forcing mandatory arguments. What you can do is test for a certain value after the getopts loop has finished.
    If -x is a mandatory option, and it is used to set the var variable, test to see if it hasn't been set by the getopts loop, and if so print a relevant message and exit:

    if [ -z ${var+x} ]; then
     echo "No -x argument supplied. exiting"
     exit 10
    fi
    

    The above runs after the case statement.

    Also, you're missing a 'done' after your while loop, most likely a typo.