Code review comment for ~paelzer/ubuntu/+source/chrony:lp-1898000-argparse-GROOVY

Revision history for this message
Bryce Harrington (bryce) wrote :

A pattern I often use with bash scripts is to pre-process the args to handle long args and other oddities, and then run it through getopts for the full processing. So for example:

for arg in "${@}"; do
    shift
    case "${arg}" in
        "-1")
            set -- "${@}" "\"-1\""
            ;;
        "--long-opt-with-val")
            set -- "${@}" "-L"
            ;;
        *)
            set -- "${@}" "${arg}"
    esac
done

Once you've handled your corner cases, you can pass "${@}" to getopts normally. Below is a fully detailed example:

#!/bin/bash

for arg in "${@}"; do
    shift
    case "${arg}" in
        "-1")
            set -- "${@}" "\"-1\""
            ;;
        "--long-opt-with-val")
            set -- "${@}" "-L"
            ;;
        *)
            set -- "${@}" "${arg}"
    esac
done

# Now, if desired, can safely run the args through getopts:
OPTIND=1
while getopts ":xdF:L:" opt "${@}"; do
    case "${opt}" in
        x) echo "-x is set" ;;
        d) echo "-d is set" ;;
        F) echo "-F = ${OPTARG}" ;;
        L) echo "Long ${OPTARG}" ;;
    esac
done
shift $(( OPTIND - 1 ))

echo "Remaining args: ${@}"

Output:

$ /tmp/chronyd-starter-x.sh -F 1 -x
-F = 1
-x is set
Remaining args:
$ /tmp/chronyd-starter-x.sh -F -1 -x
-F = "-1"
-x is set
Remaining args:
$ /tmp/chronyd-starter-x.sh -dx -F -1 foo bar
-d is set
-x is set
-F = "-1"
Remaining args: foo bar
$ /tmp/chronyd-starter-x.sh -xF -1 foo bar
-x is set
-F = "-1"
Remaining args: foo bar
$ /tmp/chronyd-starter-x.sh --long-opt-with-val foo -dx -F 1 bar baz
Long foo
-d is set
-x is set
-F = 1
Remaining args: bar baz

« Back to merge proposal