在bourne shell中使用user-defined-function中的getopts

时间:2022-09-21 00:00:33

Is it possible to pass command line arguments into a function from within a bourne script, in order to allow getopts to process them.

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

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.

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

1 个解决方案

#1


6  

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:

您可以在变量之后提供args到getopts。默认值是$ @,但这也是shell函数用来表示其参数的内容。解决方案是将“$ @” - 将所有脚本的命令行参数表示为单个字符串 - 传递给processArgs:

processArgs "$@"

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

将其添加到您的脚本(并修复第11行中的引用),并尝试一些乱码测试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

#1


6  

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:

您可以在变量之后提供args到getopts。默认值是$ @,但这也是shell函数用来表示其参数的内容。解决方案是将“$ @” - 将所有脚本的命令行参数表示为单个字符串 - 传递给processArgs:

processArgs "$@"

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

将其添加到您的脚本(并修复第11行中的引用),并尝试一些乱码测试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