我有一个文件:
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
的事情,我很乐意听到。