在 bourne shell 中的用户定义函数中使用 getopts
是否可以将命令行参数从 bourne 脚本内传递到函数中,以便允许 getopts 处理它们。
我的脚本的其余部分很好地打包到函数中,但开始看起来我必须将参数处理移至主逻辑中。
以下是现在的编写方式,但它不起作用:
processArgs() { while getopts j:f: arg do echo "${arg} -- ${OPTARG}" case "${arg}" in j) if [ -z "${filename}" ]; then job_number=$OPTARG else echo "Filename ${filename} already set." echo "Job number ${OPTARG} will be ignored. fi;; f) if [ -z "${job_number}" ]; then filename=$OPTARG else echo "Job number ${job_number} already set." echo "Filename ${OPTARG} will be ignored." fi;; esac done } doStuff1 processArgs doStuff2
是否可以以可以读取脚本参数的方式定义函数? 这可以通过其他方式完成吗? 我喜欢 getopts 的功能,但看起来在这种情况下我将不得不牺牲代码的美观来获得它。
Is it possible to pass command line arguments into a function from within a bourne script, in order to allow getopts to process them.
The rest of my script is nicely packed into functions, but it's starting to look like I'll have to move the argument processing into the main logic.
The following is how it's written now, but it doesn't work:
processArgs() { while getopts j:f: arg do echo "${arg} -- ${OPTARG}" case "${arg}" in j) if [ -z "${filename}" ]; then job_number=$OPTARG else echo "Filename ${filename} already set." echo "Job number ${OPTARG} will be ignored. fi;; f) if [ -z "${job_number}" ]; then filename=$OPTARG else echo "Job number ${job_number} already set." echo "Filename ${OPTARG} will be ignored." fi;; esac done } doStuff1 processArgs doStuff2
Is it possible to maybe define the function in a way that it can read the scripts args? Can this be done some other way? I like the functionality of getopts, but it looks like in this case I'm going to have to sacrifice the beauty of the code to get it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在变量之后向 getopts 提供 args。 默认值是 $@,但这也是 shell 函数用来表示它们的参数的方式。 解决方案是将“$@”(将脚本的所有命令行参数表示为单独的字符串)传递给 processArgs:
将其添加到脚本中(并修复第 11 行中的引用),并尝试一些乱码测试参数:
You can provide args to getopts after the variable. The default is $@, but that's also what shell functions use to represent their arguments. Solution is to pass "$@" — representing all the script's command-line arguments as individual strings — to processArgs:
Adding that to your script (and fixing the quoting in line 11), and trying out some gibberish test args: