0

Answer given here doesn't here any of my questions: bash getopts with multiple and mandatory options

I am new to shell script and trying to write a shell script with getopts meanwhile I couldn't find answers to the below questions. Can somebody please help here?

This is the script I've started writing:

 #!/bin/bash
  while getopts c:t:x: option ; do
  case $option in
    c)
      java -jar $file --fail-if-no-tests --include-classname "$OPTARG" --scan-class-path $file --include-tag regression
      ;;
    t)
      java -jar $file --fail-if-no-tests --include-classname '.*' --scan-class-path $file --include-tag "$OPTARG"
      ;;
    c | t)
      java -jar $file --fail-if-no-tests --include-classname "$OPTARG" --scan-class-path $file --include-tag "$OPTARG"
      ;;
    *)
      usage
  esac
  done
  1. How do I pass multiple flags? For example runner.sh -c classname -t tagname I Tried using ct, c|t in the getopts but did not work.
  2. How do I pass multiple arguments for one flag? For example runner.sh -g arg1 arg2
  3. Is there a way if I don't provide any flag it will run by default statement. I tried to achieve this using * but there is one issue with this approach. In case the wrong flag is provided it will always run default statement.
pk786
  • 2,140
  • 3
  • 18
  • 24
  • 1. Every flag (i.e. -c and -t) has its own argument (i.e. classname and tagname), so why do you want to use `ct` or `c|t`? You can use `ct` when flags do not take arguments I guess. 2. You can try putting arguments in quotes like `runner.sh -g "arg1 arg2"`. – nino May 07 '21 at 03:46
  • @nino 1. I need to provide an option where user can pass argument for both (-c and -t) at the same time like `runner.sh -c classname -t tagname` the script i have above only picks up `-c` because it comes first. 2. I tried using double quotes but did not work. – pk786 May 07 '21 at 03:55
  • Oh I get it now. I'll put the answer nelow. – nino May 07 '21 at 03:58
  • @nino Looks like this should work for me. Can you also advise how do I check two variables are empty or not? I am trying to use [ -z "$CLASSNAME" && -z "$TAGNAME"] but not working. – pk786 May 07 '21 at 04:32
  • I think you can use double brackets `[[ -z "$CLASSNAME" && -z "$TAGNAME"]]` or `[ -z "$CLASSNAME" ] && [ -z "$TAGNAME"]` – nino May 07 '21 at 04:43

1 Answers1

0
while getopts 'c:t:x:' option; do
    case "$option" in
        c ) classname="$OPTARG" ;;
        t ) tagname="$OPTARG" ;;
        x ) xvar="$OPTARG" ;;
    esac
done

## now you can use the variables in your command
nino
  • 554
  • 2
  • 7
  • 20