0

Due to my lack of thorough understanding using getopts, the title is definitely vague :0. I am currently writing a bash script and I would like to add an option that outputs the other options within the case statement in getopts. For the sake of scaling, I have shortened the program.

#!/bin/bash

while getopts :abc opt
do
  case $opt in
       a) 
           echo "Hello"
           ;;
       b)
           echo "Goodbye"
       c)            
           :ab #****I WANT -c TO OUTPUT THE RESULTS OF a and b************
           ;;
  esac
done

As you can see in option c, I would like this particular option (-c) to put out both the results of -a and -b. Is there a way to go about this by simply making c call on option a and b?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

2 Answers2

1

you can introduce functions to reduce duplications, something like this:

#!/bin/bash

do_a() {
  echo "Hello"
}

do_b() {
  echo "Goodbye"
}


while getopts :abc opt
do
  case $opt in
     a)
         do_a
         ;;
     b)
         do_b
         ;;
     c)    
         do_a
         do_b
         ;;
  esac
done
kofemann
  • 4,217
  • 1
  • 34
  • 39
0

If you are using a recent version of Bash, instead of terminating case clauses with ;; you could use bash specific ;;& with multiple patterns:

#!/bin/bash

while getopts :abc opt
do
    case $opt in
        a|c) 
            echo "Hello"
            ;;&
        b|c)
            echo "Goodbye"
            ;;&
    esac
done

And:

$ bash script.bash -a
Hello
$ bash script.bash -c 
Hello
Goodbye

Using ‘;;&’ in place of ‘;;’ causes the shell to test the patterns in the next clause, if any, and execute any associated command-list on a successful match.

James Brown
  • 36,089
  • 7
  • 43
  • 59