0

I want to parse one argument with getopts, which requires two other parsed arguments to be set.

So something like this, if -l is set to yes:

sh name.sh -l yes -a "bla" -b "blubb"

Then arguments -a and -b need to be set to. Otherwise these arguments can be left out.

sh name.sh -l no

My case for getopts looks like this:

    while getopts ":l:a:b:" o; do
    case "${o}" in
        l)
            l=${OPTARG}
            (( $l == "Y" || $l == "y" )) || usage;;
        a)
            a=${OPTARG}
            (( $a == "bla" || $a == "blubb" )) || usage;;
        b)
            b=${OPTARG};;
        :)
            echo "Missing option argument for -$OPTARG" >&2; exit 1;;
        *)
            usage;;
    esac
done
shift $((OPTIND-1))

if [ -z "${l}" ] || [ -z "${a}" ] || [ -z "${b}" ] ;
then
    usage
fi

But as it is right now, -a and -b are required as input and I don't know how they can be left out in the case -l is set to no, so that they don't have to be entered. Like I would call them see mentioned above. Thanks:)

Momina
  • 41
  • 1
  • 8
  • You cannot stop the user from entering any options. Either you can ignore `-a` and `-b` if `-l` is passed with `no` or you can throw an error. – Fazlin Sep 02 '16 at 19:56
  • There must be a way, if -l option is set, that i can check if the other options -a and -b are set. And that if it is not set, that the other options are not required – Momina Sep 03 '16 at 09:53
  • @Fazlin How do I ignore -a and -b if -l is passed with no? – Momina Sep 03 '16 at 10:30
  • just add an `if` condition that if `-l` is no, then `unset` variables `a` and `b` – Fazlin Sep 04 '16 at 08:30
  • or you can just not use `$a` and `$b` if `-l` is no – Fazlin Sep 04 '16 at 08:31

0 Answers0