在 bourne shell 的用户定义函数中使用 getopts [英] Using getopts within user-defined-function in bourne shell

查看:36
本文介绍了在 bourne shell 的用户定义函数中使用 getopts的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从 bourne 脚本中将命令行参数传递到函数中,以允许 getopts 处理它们.

我的脚本的其余部分很好地打包到函数中,但看起来我必须将参数处理移到主逻辑中.

下面是现在的写法,但是不行:

<前>进程参数(){而 getopts j:f: arg做echo "${arg} -- ${OPTARG}"案例${arg}"在j) 如果 [ -z "${文件名}" ];然后作业编号=$OPTARG别的echo "文件名 ${filename} 已经设置."echo "作业号 ${OPTARG} 将被忽略.菲;;f) 如果 [ -z "${job_number}" ];然后文件名=$OPTARG别的echo "作业号 ${job_number} 已经设置."echo "文件名 ${OPTARG} 将被忽略."菲;;esac完毕}doStuff1进程参数doStuff2

是否有可能以一种可以读取脚本参数的方式定义函数?这可以通过其他方式完成吗?我喜欢 getopts 的功能,但看起来在这种情况下我将不得不牺牲代码的美感来获得它.

解决方案

你可以在变量之后提供 args 给 getopts.默认值是 $@,但这也是 shell 函数用来表示它们的 参数的方式.解决方案是通过$@"—将所有脚本的命令行参数表示为单独的字符串 —处理参数:

<前>processArgs "$@"

将其添加到您的脚本中(并修复第 11 行中的引用),并尝试一些乱七八糟的测试参数:

<前>$ ./try -j asdf -f fooo -fasdfasdf -j424pyagnasdj -- 自卫队f——噗作业号 asdf 已设置.文件名 fooo 将被忽略.f -- asdfasdf作业号 asdf 已设置.文件名 asdfasdf 将被忽略.j -- 424pyagnasd

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.

解决方案

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:

processArgs "$@"

Adding that to your script (and fixing the quoting in line 11), and trying out some gibberish test args:

$ ./try -j asdf -f fooo -fasdfasdf -j424pyagnasd
j -- asdf
f -- fooo
Job number asdf already set.
Filename fooo will be ignored.
f -- asdfasdf
Job number asdf already set.
Filename asdfasdf will be ignored.
j -- 424pyagnasd

这篇关于在 bourne shell 的用户定义函数中使用 getopts的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆