Home > Blockchain >  Turning a positional argument in to a custom set to use with getopts in bash
Turning a positional argument in to a custom set to use with getopts in bash

Time:05-17

I'm using a script in Jamf which uses positional arguments, but I need to use getopts to parse the various arguments only from #4.

Positions 1-3 are static and get passed from Jamf as "/", the host name and the user name, respectively. In position 4, I'm sending the actual arguments I need to use in my while loop. I want to be able to build and add "${my_arr[@]}" after "opt":

OPTIND=4
while getopts "o:O:p:t:T:v:c:fsr?" opt
do
    case "${opt}" in
        o) osMinVers=${OPTARG}
            echoFunc "OPTARG: $OPTARG"
            ;;
        O) osMaxVers=${OPTARG};;
        p) appPath=${OPTARG};;
        t) jamfTrigger=${OPTARG};;
        T) patchName=${OPTARG};;
        v) appToUpdVers=${OPTARG};;
        c) verCheck=${OPTARG};;
        f) installIfMissing="true";;
        s) silent="true";;
        r) reboot="true";;
        ?) echo "Usage: script.sh -o -O -p -t -T -v [-f -s -r]";
           echo "      -o <osMinVers>";
           echo "      -O <osMaxVers>";
           echo "      -p <appPath>";
           echo "      -t <jamfPatchTrigger>";
           echo "      -T <patchName>";
           echo "      -v <appToUpdVers>";
           echo "      -c Greater then or less then";
           echo "         g/G = application must be greater than the version specified";
           echo "         l/L = application must be less than the version specified";
           echo "      -f Install if Missing";
           echo "      -s Silent";
           echo "      -r Reboot";
           exitFunc 90
    esac
done

The way this script would be run is:

sh /path/to/script.sh "/" "hostname" "username" "-o 18G1 -O 22Z9999 -p \"/Applications/Symantec Endpoint Protection.app\" -t SEPRemoval -T \"Symantec Removal\" -v 14.3.5055.3000"

CodePudding user response:

I believe that getopts stops at the first non-option argument, and I don't think setting OPTIND works around it. I'm happy to be corrected.

I would do:

path=$1
host=$2
user=$3
shift 3

while getopts "o:O:p:t:T:v:c:fsr?" opt
...

CodePudding user response:

You script should work if you call it with :

sh /path/to/script.sh "/" "hostname" "username" -o 18G1 -O 22Z9999 -p "/Applications/Symantec Endpoint Protection.app" -t SEPRemoval -T "Symantec Removal" -v 14.3.5055.3000
  • Related