通过参数壳转义字符串中的Bourne shell子命令 [英] Pass shell-escaped string of arguments to a subcommand in Bourne shell
问题描述
说我有一个命令,我想运行( CMD
),并包含我要传递给函数(类似的参数变量--foo这样的酒吧巴兹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
这,当然,结果符合的四的参数运行以下命令: - 富
,'栏
,巴兹
和 qux
。另一种方法我已经习惯了(即使用$ @
时)presents一个不同的问题:
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"
这与执行命令的有一个的说法: - 富'酒吧巴兹qux
This executes the command with one argument: --foo 'bar baz' qux
.
我如何运行命令的三的参数( - 富
,酒吧巴兹
和 qux
)如预期?
How can I run the command with three arguments (--foo
, bar baz
, and qux
) as intended?
推荐答案
一种可能性是使用评估
:
#!/bin/sh
args="--foo 'bar baz' qux"
cmd="python -c 'import sys; print sys.argv'"
eval $cmd $args
这样,你会在命令行是间preTED而不是仅仅根据 IFS
分裂。这使输出:
$ ./args.sh
['-c', '--foo', 'bar baz', 'qux']
所以,你可以看到你想要的ARG游戏通过。
So that you can see the args are passed as you wanted.
这篇关于通过参数壳转义字符串中的Bourne shell子命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!