1

我们有一个getopts脚本来检索如下参数

#!/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

我们收到一个在另一个脚本中解析并传递给getopts脚本的参数,它适用于单个条目,例如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

但是,我们收到多个条目,例如12345,-d somedesc -l somelabel:6789, -d anotherdesc -l anotherlabel,并且正在使用loopawk进一步拆分参数,在这种情况下,getopts即使正确传递了 OPTIONS,也不会触发。

#!/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

有什么原因getopts无法识别 OPTIONS 吗?

4

1 回答 1

1

问题是您将脚本顶部的 IFS 值更改为冒号:,然后test.sh在 IFS 仍设置为时将参数传递给脚本:。实际上被称为:

第一次:

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

第二次:

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
于 2013-07-16T05:53:02.847 回答