0

Can some one tell me how to parse the following command line options with getopt?

myCmd [[-f <file> | -k | -v] -e <env> -h help]

where

f, k and v are mutually exclusive. f and e both need a parameter, but k and v do not.

So the command can be:

  • mycmd -f file -e aaa or
  • mycmd -v -e aaa or
  • mycmd -k -e aaa

I have tried the following:

while getopts "f:kve:" o
    do
    case "$o" in
       f | k | v) process_file ;;
       k) process_key ;;
       v) process_var ;;
       e) process_env ;;
       *) print_help ;;
    esac
 done;

That does not seem to work. Any help is appreciated.

2
  • What do you mean with "does not work"? What behaviour do you expect? Commented Oct 4, 2017 at 18:18
  • I can not get f, k or v to be mutually exclusive Commented Oct 4, 2017 at 18:25

1 Answer 1

1

You need to add that logic yourself. This is untested:

file=""
has_k=false
has_v=false
env=""

while getopts "f:kve:" opt; do
    case "$opt" in
        f) file="$OPTARG" ;;
        k) has_k=true ;;
        v) has_v=true ;;
        e) env="$OPTARG" ;;
        *) print_help; exit 1 ;;
    esac
done
shift $((OPTIND - 1))

if  ( [[ -n $file ]] && $has_k ) ||
    ( [[ -n $file ]] && $has_v ) ||
    ( $has_k && $has_v )
then
    echo "May only specify one of -f,-k,-v"
    print_help
    exit 1
fi
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.