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.