2

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
Kim
  • 23
  • 3
  • This might help: [An example of how to use getopts in bash](https://stackoverflow.com/q/16483119/3776858) – Cyrus Apr 07 '18 at 10:14
  • @Cyrus Yes thank you I have seen it before. I am just a beginner, I still can't figure this out. – Kim Apr 07 '18 at 10:23

1 Answers1

0

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.

Evya
  • 2,325
  • 3
  • 11
  • 22
  • Thank you so much! It's working now! Can you also help me how to input these values in any order? – Kim Apr 07 '18 at 14:47
  • @Kim, As each argument is not dependent on the others, their order is arbitrary and can be changed freely. – Evya Apr 07 '18 at 15:03
  • OHH, I must have a typo before. Everything is fine now, thanks again! – Kim Apr 07 '18 at 15:07