1

I have a file:

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 "$@"

That performs correctly:

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

However, if I have the same function in my ~/.bashrc file, I get:

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

I do notice something weird about 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)

EDIT HA! Found the solution here Using getopts inside a Bash function

This works:

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
}

If anyone wants to explain the local issue, I'd love to hear. Furthermore, if anyone wants to explain the which getopts thing, I'd love to hear that to.

Community
  • 1
  • 1
abalter
  • 9,663
  • 17
  • 90
  • 145
  • Does the line involving setting `export PATH` appear before the function definition or after in `.bashrc` – Inian Feb 18 '17 at 08:04
  • @Inian Before the function. What do you get with `which getopts`? – abalter Feb 18 '17 at 08:05
  • Are you sure you are updating the path elsewhere in `.bashrc`, because the problem seems to be it could not find the path where `getopts` is installed, at the instance when you are running the function. – Inian Feb 18 '17 at 08:07
  • 1
    Turns out it's finding getopts (somehow). The problem was local variables! – abalter Feb 18 '17 at 08:07
  • 1
    Nice that you have caught it, but I am closing this question to post as duplicate of the one you shared, so that you don't attract opinionated answers (or) spam here. – Inian Feb 18 '17 at 08:38

0 Answers0