问题描述
在bash脚本中,我需要将参数传递给另一个程序.参数中有空格,因此必须用引号引起来.在这种简单情况1中,一切正常:
In a bash script, I need to pass a parameter to another program. The parameter has spaces in so must be quoted. Everything works fine in this simple case 1:
/bin/echo /some/command --param="abc def ghi"
输出:
/some/command --param=abc def ghi
如果我想使bash脚本更加复杂,那么问题就开始了,在情况2和3中,参数值有所改变.
The problem begins if I want to make the bash script more sophisticated, somehow the parameter value has changed in case 2 and 3:
FOO="ghi"
DEFAULTS="--param=\"abc def $FOO\""
/bin/echo /some/command $DEFAULTS
DEFAULTS='--param="abc def '$FOO'"'
/bin/echo /some/command $DEFAULTS
输出:
/some/command --param="abc def ghi"
/some/command --param="abc def ghi"
abc def ghi
周围的双引号在2和3中显示,而在1中没有显示.
The double quotes surrounding abc def ghi
are shown in 2 and 3, whereas they are not shown for 1.
通过/some/command实际打印它作为第一个参数收到的内容,可以更好地说明这一点.在这里,整个字符串"abc def ghi"
作为param
参数的值被接收:
This is better illustrated by having /some/command actually print what it receives as the first parameter. Here the whole string "abc def ghi"
is received as the value of the param
parameter:
perl -le'print $ARGV[0]' param="abc def ghi"
输出(右):
param=abc def ghi
但是这里只收到"abc
,并带有一个引号:
But here only "abc
is received, with one leading quote:
DEFAULTS='param="abc def ghi"'
perl -le'print $ARGV[0]' $DEFAULTS
DEFAULTS="param=\"abc def ghi\""
perl -le'print $ARGV[0]' $DEFAULTS
输出(错误):
param="abc
param="abc
如何使用bash动态构造类似param="abc def ghi"
的字符串并将其原封不动地传递给另一个命令?
How do I use bash to dynamically construct a string like param="abc def ghi"
and be able to pass it intact to another command?
推荐答案
使用数组;这就是为什么引入它们的原因.
Use an array; this is why they were introduced.
FOO="ghi"
# Contains one element, but not the literal quotes
DEFAULTS=(--param="abc def $FOO")
# command gets 1 argument, the single element of the array
/some/command "${DEFAULTS[@]}"
# Two elements
DEFAULTS=(--param="abc def $FOO" --other="foo bar")
# command gets 2 arguments
/some/command "${DEFAULTS[@]}"
这篇关于如何将引用的参数传递给另一个程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!