1

I have a myscript.sh which starts like this:

#!/usr/bin/env bash
set -e

usage(){
  echo "Show Usage ... Blah blah"
  exit 1
}

if [ $# = 0 ]; then
  usage;
fi

while true; do
  case "$1" in
    -l | --build-lib ) BUILD_LIB=true; 
    --other-option ) OTHER_OPTION=$2; shift; shift;;
    -h | --help ) usage; shift;;
    * ) break ;;
  esac
done

# I do my thing here ....
echo "Do my thing"

I am not sure if this is the best way to parse the parameters but so far I have a problem. I am not correctly breaking/failing when the user passes wrong or unknown parameters. How can I address this correctly?

for example I want to avoid calls like:

$ ./myscript.sh unknownParameter

1 Answer 1

3

You need to exit when an incorrect option is given, not just break out of the loop. Easiest way is to call your usage function.

while [ $# -gt 0 ]; do
  case "$1" in
    -l | --build-lib ) BUILD_LIB=tru ;;
    --xcode-dev-path ) XCODE_DEV_PATH=${2%/}; shift ;;
    -h | --help ) usage;;
    * ) usage ;;
  esac
  shift
done
Sign up to request clarification or add additional context in comments.

5 Comments

I see that you are using one shitf;; less than me after checking each parameter. How come this is posible? I thought shift was needed to go to the next parameter. - I am kind of lost in shell.
I added shift at the bottom of the loop. You always need to shift after each arg, so it's redundant to put that one in each case.
This didn't work as expected. Indeed, I can now avoid calls like $ ./myscript.sh unknownParameter but now I cannot even pass correct parameters like $ ./myscript.sh -l since *) is apparently always reached :(
I fixed the missing ;; after the -h case, and changed the while condition so the loop will exit. Does that help? Why aren't you using getopt, anyway?
It worked! Thank you very much. I guess I should learn how to use getopt for proper argument handling.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.