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.
5
  • 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". Commented May 7, 2021 at 3: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. Commented May 7, 2021 at 3:55
  • Oh I get it now. I'll put the answer nelow. Commented May 7, 2021 at 3: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. Commented May 7, 2021 at 4:32
  • I think you can use double brackets [[ -z "$CLASSNAME" && -z "$TAGNAME"]] or [ -z "$CLASSNAME" ] && [ -z "$TAGNAME"] Commented May 7, 2021 at 4:43

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.