-1

I'm writing a Bash script that has the following usage:

ci-badge -t|-a [-b branch] [-m] [-d description] [-l [link] ] repo

Examples:

$ ci-badge -t foo/bar
$ ci-badge -ab dev foo/bar -m
$ ci-badge quux/bar -md 'Hello, world.'

More samples can be found here on GitHub. Anyway, I'm wondering exactly how to implement argument parsing for this script using getopts. After a few hours looking at this basic getopts guide and scouring SO, this is what my code looks so far:

#!/usr/bin/env bash

generate_url=false # set to true if -l is passed with no arg
markdown=false # true -> surround the URL with markdown

# Parse options
while getopts ':tab:md:l:' opt
do
    case "$opt" in
        a) service=appveyor ;;
        b) branch=$OPTARG ;;
        d) description=$OPTARG ;;
        l) url=$OPTARG ;;
        m) markdown=true ;;
        t) service=travis ;;
        # Colon: runs if no args are passed to
        # an option that normally requires parameters.
        :) test "$OPTARG" = l && generate_url=true ;;
        # ?: Runs if an invalid option is passed.
        '?') die ;;
    esac
done

As you can see, most of the functionality is there, but I'm wondering how to accept repo as an argument to the script. Since getopts stops parsing after it encounters the first non-option argument, I'm wondering, how would I implement this (preferably with minimal complexity)? The guide I linked earlier doesn't seem to mention dealing with arguments that aren't associated with an option, so I'm a bit lost.

Thanks for helping!

James Ko
  • 32,215
  • 30
  • 128
  • 239
  • @ConspicuousCompiler The question/answer you linked to does not handle any arguments that aren't tied to an option, unfortunately. – James Ko Apr 19 '16 at 02:07
  • doesn't `case "$opt" in ..... ;; * ) unpaired_arg=$1 ; other_stuff with "$unpaired_arg" ; .. more ... ;; esac` get you most of the way there? Good luck. – shellter Apr 19 '16 at 02:54
  • @JamesKo Note that I said "scroll down to the getopt solution". It very specifically handles options beyond what getopt processes. – Conspicuous Compiler Apr 19 '16 at 06:32

1 Answers1

0

Use $OPTIND value. After getopts cycle:

shift $((OPTIND-1))
echo $@
echo $1 $2 ...