getopts不在.bashrc中工作

时间:2017-02-18 07:57:02

标签: bash getopts

我有一个文件:

argtest

#!/bin/bash

function parse ()
{
    echo "in parse"
    echo "starting to parse args $@"

    while getopts "pq:" opt; do
        echo "parsing arg $opt"

        case "$opt" in
            p)  echo "got option p" ;;
            q)  echo "got option q with value ${OPTARG}" ;;
        esac

    done
}

parse "$@"

执行正确:

balter$ bash argtest -pq 9
in parse
starting to parse args -pq 9
parsing arg p
got option p
parsing arg q
got option q with value 9
balter$ source argtest
in parse
starting to parse args
balter$ parse -pq 9
in parse
starting to parse args -pq 9
parsing arg p
got option p
parsing arg q
got option q with value 9

但是,如果我在~/.bashrc文件中具有相同的功能,我会得到:

balter$ tail -16 ~/.bashrc
function parse ()
{
    echo "in parse"
    echo "starting to parse args $@"

    while getopts "pq:" opt; do
        echo "parsing arg $opt"

        case "$opt" in
            p)  echo "got option p" ;;
            q)  echo "got option q with value ${OPTARG}" ;;
        esac

    done
}

balter$ source ~/.bashrc
balter$ parse -pq 9
in parse
starting to parse args -pq 9

我确实注意到getopts

的奇怪之处
balter$ getopts
getopts: usage: getopts optstring name [arg]
balter$ which getopts
which: no getopts in (<other paths>:/bin:/usr/local/bin:/usr/bin:/opt/condor/bin)

修改 哈!在此处找到了解决方案Using getopts inside a Bash function

这有效:

function parse ()
{
    echo "in parse"
    echo "starting to parse args $@"

    local OPTIND
    local OPTARG
    local opt

    while getopts "pq:" opt; do
        echo "parsing arg $opt"

        case "$opt" in
            p)  echo "got option p" ;;
            q)  echo "got option q with value ${OPTARG}" ;;
        esac

    done
}

如果有人想解释local问题,我很乐意听到。此外,如果有人想解释which getopts的事情,我很乐意听到。

0 个答案:

没有答案