Bash脚本参数

时间:2017-02-03 08:59:28

标签: bash getopts

我试图将参数传递给我写的脚本,但是不能正确。

我想要的是一个没有标志的强制参数,以及两个带标志的可选参数,所以它可以这样调用:

 Dim FindString As Range
 Dim Rng As Range

        FindString = Worksheets("Sheet1").Range("I2" &  _
        .Range("I" & .Rows.Count).End(xlUp).Row + 1).Value

        If Trim(FindString) <> "" Then
            With Sheets("Sheet2").Range("A1:AZ500")
                Set Rng = .Find(What:=FindString, _
                                After:=.Cells(.Cells.Count), _
                                LookIn:=xlValues, _
                                LookAt:=xlWhole, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlNext, _
                                MatchCase:=False)
                If Not Rng Is Nothing Then
                    'Application.Goto Rng, True
                Else

                End If
            End With
        End If

        With Rng.Interior
            .Pattern = xlSolid
            .Color = 255
        End With

./myscript mandatory_arg -b opt_arg -a opt_arg

我看了一下getopts并得到了这个:

./myscript mandatory_arg -a opt_arg
./myscript mandatory_arg -b opt_arg

但它根本不起作用。

1 个答案:

答案 0 :(得分:3)

假设您的强制参数出现最后,那么您应该尝试以下代码: [comments inline]

OPTIND=1
while getopts "b:a:" option
do
    case "${option}"
    in
        b) MERGE_BRANCH=${OPTARG};;
        a) ACTION=${OPTARG};;
    esac
done

# reset positional arguments to include only those that have not
# been parsed by getopts

shift $((OPTIND-1))
[ "$1" = "--" ] && shift

# test: there is at least one more argument left

(( 1 <= ${#} )) || { echo "missing mandatory argument" 2>&1 ; exit 1; };

echo "$1"
echo "$MERGE_BRANCH"
echo "$ACTION"

结果:

~$ ./test.sh -b B -a A test
test
B
A
~$ ./tes.sh -b B -a A
missing mandatory argument

如果你真的希望强制性参数出现第一个,那么你可以做以下事情:

MANDATORY="${1}"
[[ "${MANDATORY}" =~ -.* ]] && { echo "missing or invalid mandatory argument" 2>&1; exit 1; };

shift # or, instead of using `shift`, you can set OPTIND=2 in the next line   
OPTIND=1
while getopts "b:a:" option
do
    case "${option}"
    in
        b) MERGE_BRANCH=${OPTARG};;
        a) ACTION=${OPTARG};;
    esac
done

# reset positional arguments to include only those that have not
# been parsed by getopts

shift $((OPTIND-1))
[ "$1" = "--" ] && shift

echo "$MANDATORY"
echo "$MERGE_BRANCH"
echo "$ACTION"

结果如下:

~$ ./test.sh test -b B -a A
test
B
A
~$ ./tes.sh -b B -a A
missing or invalid mandatory argument