1

To add options, I have the following in one of my scripts:

parse_opts() {
    while [ $# -gt 0 ]; do
    case "$1" in
        -h|--help)
        help=1
        shift
        ;;
        -r|--raw)
        raw=1
        shift
        ;;
        -c|--copy)
        copy=1
        shift
        ;;
        -s|--sensitive)
        sensitive=1
        shift
        ;;
        -i|--insensitive)
        insensitive=1
        shift
        ;;
        *)
        shift
        ;;
    esac
    done
}

There is only one problem, I cannot use multiple options at the same time. For example, using -r -s works but using -rs does not. How can I programmatically make it work without adding separate entries? The shell I am using is sh.

16
  • which shell is this, specifically? Because zsh does bring a much more powerful option parser. (I'll be honest, I still think "easy to use" is still different, but at least it's possible to implement this if you follow a fixed recipe) Commented Jul 5, 2022 at 7:22
  • 2
    Have you heard of getopts? Commented Jul 5, 2022 at 8:39
  • 4
    @FelixJN, only the getopts from ksh93 does long options though (and not even the same was as GNU getopt_long() does). util-linux getopt can do it though. Commented Jul 5, 2022 at 10:06
  • 1
    @Amarakon If you have a solution for your specific use case, then consider posting a proper answer. Commented Jul 6, 2022 at 7:48
  • 1
    You linked my answer on Stack Overflow and used it to refine your answer, but I think you missed that its use of getopts makes it vastly more capable than your own implementation. For example, your code doesn't support combining options, like -rc, nor does your code complain given invalid options, nor does it support arguments to options. Follow that link for a better solution implementing long and short options with optional arguments and proper errors. Commented Mar 8, 2023 at 19:54

1 Answer 1

0

Moved from edit-to-question:

I figured out how to do it. It is based on this stackoverflow answer. I copied and pasted it but replaced it with what I need.


New code:

while getopts hcsi-: OPT; do
    # Support long options: https://stackoverflow.com/a/28466267/519360
    if [ "$OPT" = "-" ]; then
        OPT="${OPTARG%%=*}"
        OPTARG="${OPTARG#$OPT}"
        OPTARG="${OPTARG#=}"
    fi
    case "$OPT" in
        h|help) help; exit 0 ;; # Call the `help´ function and exit.
        c|copy) copy=1 ;;
        s|sensitive) case_sensitivity="sensitive" ;;
        i|insensitive) case_sensitivity="insensitive" ;;
        ??*) printf '%s\n' "Illegal option --$OPT" >&2; exit 2 ;;
        ?) exit 2 ;; # Error reported via `getopts´
    esac
done

shift $((OPTIND-1)) # Remove option arguments from the argument list

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.