遍历传递给bash脚本选项,并引述/不带引号的参数 [英] Iterating over options and quoted/unquoted arguments passed to bash script

查看:152
本文介绍了遍历传递给bash脚本选项,并引述/不带引号的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用getopt的解析它的参数bash脚本。它能够正确处理开关和长选项,以及作为参数,并引述论据,但我无法弄清楚如何遍历由反引号返回的选项/参数字符串。是这样的:

I have a bash script that uses getopt to parse its parameters. It correctly handles switches and long options, as well as arguments and quoted arguments, but I cannot figure out how to iterate over the options/arguments string returned by the backticks. Something like:

params=`getopt -o ab -l ccc  -- "$@"`
echo $params
for param in "$params"
do
echo $param
done

将回声出 -a - '富''富巴当脚本调用为 ./ a.sh -a富富巴,但循环而不是遍历每个单独只会在整个字符串运行一次。删除双引号:

Will echo out -a -- 'foo' 'foo bar' when the script is invoked as ./a.sh -a foo "foo bar", but the loop rather than iterating over each separately will only run once over the entire string. Removing the double quotes:

for param in $params

将导致其迭代是这样的:

will cause it to iterate like this:

-a
--
'foo'
'foo
bar'

忽略围绕富巴的引用。有一个简单的方法来解决这个问题?

ignoring the quoting around "foo bar". Is there a simple way to fix this?

推荐答案

从getopt的手册页(至少使用util-linux的一种:)

From the getopt manpage (at least the util-linux one:)

传统的实现(1)是无法应付
  在争论的空白等(具体外壳)的特殊字符
  和非选项参数。为了解决这个问题,这个实施
  可以生成报价输出,必须再次由PTED间$ P $
  壳(通常是通过使用eval命令)。这具有pre型的效果
  服这些字符,但你必须在某种程度上是调用getopt的无
  与其他版本(第二或第三格式更长兼容
  该概要)。为了确定这是否增强getopt的版本(1)
  安装,一个特殊的测试选项(-T)都可以使用。

Traditional implementations of getopt(1) are unable to cope with whitespace and other (shell-specific) special characters in arguments and non-option parameters. To solve this problem, this implementation can generate quoted output which must once again be interpreted by the shell (usually by using the eval command). This has the effect of pre‐ serving those characters, but you must call getopt in a way that is no longer compatible with other versions (the second or third format in the SYNOPSIS). To determine whether this enhanced version of getopt(1) is installed, a special test option (-T) can be used.

例如:

$ getopt -- 'abc' -a -b 'foo bar' -c
-a -b -c -- 'foo bar'

所以,你可以看到输出是引用,随时可以使用的:

So, you can see the output is quoted, ready to be used:

$ eval set -- "`getopt -- 'abc' -a -b 'foo bar' -c`"
$ for a; do echo "arg: $a"; done
arg: -a
arg: -b
arg: -c
arg: --
arg: foo bar

这篇关于遍历传递给bash脚本选项,并引述/不带引号的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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