使用bash函数getopts的内 [英] Using getopts inside a Bash function
问题描述
我想使用 getopts的
,我在我的.bash_profile定义一个函数内。
我们的想法是,我想在一些标志传递给这个函数来改变它的行为。
I'd like to use getopts
inside a function that I have defined in my .bash_profile.
The idea is I'd like to pass in some flags to this function to alter its behavior.
这里的code:
function t() {
echo $*
getopts "a:" OPTION
echo $OPTION
echo $OPTARG
}
当我调用它是这样的:
t -a bc
我得到这样的输出:
I get this output:
-a bc
?
有什么不对?我想获取值 BC
无需手动换挡和解析。我如何使用 getopts的
正确的一个函数里?
What's wrong? I'd like to get the value bc
without manually shifting and parsing. How do I use getopts
correctly inside a function?
编辑:纠正我的code段尝试$ OPTARG,都无济于事。
corrected my code snippet to try $OPTARG, to no avail
编辑#2:OK原来的code是很好,我的shell在某种程度上搞砸。打开一个新窗口解决它。该ARG值的确是$ OPTARG。
EDIT #2: OK turns out the code is fine, my shell was somehow messed up. Opening a new window solved it. The arg value was indeed in $OPTARG.
推荐答案
由于@Ansgar指出,参数您的选择存储在 $ {OPTARG}
,但这不是要注意使用函数里面 getopts的
时的唯一的事。您还需要通过要么你重置,或宣布其本地
确保 $ {OPTIND}
是本地功能,否则你会多次调用该函数时遇到意外的行为。
As @Ansgar points out, the argument to your option is stored in ${OPTARG}
, but this is not the only thing to watch out for when using getopts
inside a function. You also need to make sure that ${OPTIND}
is local to the function by either unsetting it or declaring it local
, otherwise you will encounter unexpected behaviour when invoking the function multiple times.
t.sh
:
#!/bin/bash
foo()
{
foo_usage() { echo "foo: [-a <arg>]" 1>&2; exit; }
local OPTIND o a
while getopts ":a:" o; do
case "${o}" in
a)
a="${OPTARG}"
;;
*)
foo_usage
;;
esac
done
shift $((OPTIND-1))
echo "a: [${a}], non-option arguments: $*"
}
foo
foo -a bc bar quux
foo -x
运行示例:
$ ./t.sh
a: [], non-option arguments:
a: [bc], non-option arguments: bar quux
foo: [-a <arg>]
如果您注释掉#本地OPTIND
,这就是你所得到的,而不是:
If you comment out # local OPTIND
, this is what you get instead:
$ ./t.sh
a: [], non-option arguments:
a: [bc], non-option arguments: bar quux
a: [bc], non-option arguments:
除此之外,它的使用是相同的函数之外使用时作为
Other than that, its usage is the same as when used outside of a function.
这篇关于使用bash函数getopts的内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!