将 shell 转义的参数字符串传递给 Bourne shell 中的子命令 [英] Pass shell-escaped string of arguments to a subcommand in Bourne shell
问题描述
假设我有一个要运行的命令 (cmd
) 和一个包含要传递给函数的参数的变量(类似于 --foo 'bar baz' qux代码>).像这样:
Say I have a command I want to run (cmd
) and a variable containing the arguments I want to pass to the function (something like --foo 'bar baz' qux
). Like so:
#!/bin/sh
command=cmd
args="--foo 'bar baz' qux"
参数包含引号,就像上面显示的那样,将包含空格的参数组合在一起.然后我想运行命令:
The arguments contain quotes, like the ones shown above, that group together an argument containing a space. I'd then like to run the command:
$command $args
当然,这会导致运行带有四个参数的命令:--foo
、'bar
、baz'
和 qux
.我习惯的替代方案(即,当使用 "$@"
时)提出了一个不同的问题:
This, of course, results in running the command with four arguments: --foo
, 'bar
, baz'
, and qux
. The alternative I'm used to (i.e., when using "$@"
) presents a different problem:
$command "$args"
这会执行带有 one 参数的命令:--foo 'bar baz' qux
.
This executes the command with one argument: --foo 'bar baz' qux
.
如何使用 三个 参数(--foo
、bar baz
和 qux
)运行命令)如预期?
How can I run the command with three arguments (--foo
, bar baz
, and qux
) as intended?
推荐答案
一种可能是使用eval
:
#!/bin/sh
args="--foo 'bar baz' qux"
cmd="python -c 'import sys; print sys.argv'"
eval $cmd $args
通过这种方式,您可以解释命令行,而不仅仅是根据 IFS
进行拆分.这给出了输出:
That way you cause the command line to be interpreted rather than just split according to IFS
. This gives the output:
$ ./args.sh
['-c', '--foo', 'bar baz', 'qux']
这样你就可以看到参数是按照你想要的方式传递的.
So that you can see the args are passed as you wanted.
这篇关于将 shell 转义的参数字符串传递给 Bourne shell 中的子命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!