문제

We have a getopts script to retrieve the arguments as below

#!/bin/bash
while getopts ":d:l:f:o:" OPT;
do
    echo 'In Test Script - Got Options '$OPT ' with' $OPTIND ' and ' $OPTARG
    case $OPT in
        d)
            echo $OPTARG;;
        f)
            echo $OPTARG;;
        l)
            echo $OPTARG;;
        ?)
            echo $OPTARG;;
    esac
done

We receive an argument which is parsed in another script and passed to the getopts script and it works fine for single entry e.g. 12345,-d somedesc -l somelabel

#!/bin/bash
INFO="12345,-d somedesc -l somelabel"
ID=`echo "$INFO" | awk -F "," "{ print $"1" }"`
OPTIONS=`echo "$INFO" | awk -F "," "{ print $"2" }"`
sh test.sh $OPTIONS

However, we receive multiple entries e.g. 12345,-d somedesc -l somelabel:6789, -d anotherdesc -l anotherlabel and are using loop and awk to split the arguments further in which case the getopts does not get triggered even though the OPTIONS are correctly passed.

#!/bin/bash
INFO="12345,-d somedesc -l somelabel:6789, -d anotherdesc -l anotherlabel"
IFS=":"
set $INFO
echo 'Parsing INFO '$INFO
for item
do
    echo 'Item is '$item
    #parsing each item to separate id and options
    ID=`echo "$item" | awk -F "," "{ print $"1" }"`
    echo 'ID is '$ID
    OPTIONS=`echo "$item" | awk -F "," "{ print $"2" }"`
    echo 'Invoking Test Script with '$OPTIONS
    sh test.sh $OPTIONS
done

Any reason the getopts is not able to recognize the OPTIONS ?

도움이 되었습니까?

해결책

Problem is that you're changing value of IFS on top of your script to colon : and then passing arguments to your script test.sh while IFS is still set to :. Which in effect is being called as:

1st time:

sh test.sh "-d somedesc -l somelabel"

and 2nd time:

sh test.sh " -d anotherdesc -l anotherlabel"

Thus making argument list into a single argument and getops fails.

What you need to do is to save original IFS before you set it to colon and restore it after set command like this:

#!/bin/bash
INFO="12345,-d somedesc -l somelabel:6789, -d anotherdesc -l anotherlabel"
# save IFS value
OLDIFS=$IFS
IFS=":"
set $INFO
# restore saved IFS value
IFS=$OLDIFS

echo 'Parsing INFO '$INFO
for item
do
    echo 'Item is '$item
    #parsing each item to separate id and options
    ID=`echo "$item" | awk -F "," "{ print $"1" }"`
    echo 'ID is '$ID
    OPTIONS=`echo "$item" | awk -F "," "{ print $"2" }"`
    echo 'Invoking Test Script with '$OPTIONS
    sh test.sh $OPTIONS
done
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top