1

I want to run a script which accepts 3 command line options -o|q|i. I want to make the q and o but not i so run command has to look like:

script.sh -q <some-text> -o <some-other-text>

The below code makes none of them mandatory. How can I achieve this?

 for arg in "$@"
    do
        case $arg in
            -q) req="$2"
            shift  shift ;;
            -o) out="$2"
            shift  shift ;;
            -i|) ind="$2"
            shift  shift ;;
        esac
    done
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
bcsta
  • 1,963
  • 3
  • 22
  • 61
  • @thatotherguy how can I then show a `-help` flag if they are not set? – bcsta Feb 03 '22 at 20:21
  • 1
    You might want to take a look at `getopts` – Fravadona Feb 03 '22 at 20:24
  • 3
    You're mixing two different (incompatible) ways of parsing arguments, the `for` loop and the `shift`/`$2` method. Use `getopts` instead -- see [BashFAQ #35](http://mywiki.wooledge.org/BashFAQ/035) and [tzelleke's answer here](https://stackoverflow.com/questions/12036445/command-line-arguments-in-bash/12036574#12036574). More examples (and more complex methods) [here](https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash). – Gordon Davisson Feb 03 '22 at 20:35
  • It doesn't really make sense for _options_ to not be _optional._ – tripleee Feb 06 '22 at 09:11
  • @tripleee seems like a semantic point you are making correct? Or are you implying that this is not the way to setup mandatory arguments in shell? I am open to other ideas. – bcsta Feb 06 '22 at 09:16
  • A common arrangement is to simply require positional arguments without options, like `cp from to` rather than `cp --src=from --dst=to` – tripleee Feb 06 '22 at 09:20

1 Answers1

0

I made this work by checking that the variables req and out have some value after the for loop with the below code:

  if [[ -z $out  ||  -z $req ]]
  then
    echo "ERROR: -q  and -o are mandatory arguments. See usage: \n";
    exit 1;
  fi
bcsta
  • 1,963
  • 3
  • 22
  • 61