2014-02-20 224 views
0

我要执行的命令:时只需在终端执行猛砸单引号

xcodebuild -exportArchive -exportFormat IPA -archivePath myApp.xcarchive -exportPath myApp.ipa -exportProvisioningProfile 'myApp adhoc' 

上面的命令工作正常。但是,我试图在bash中的包装函数中执行命令。包装函数通过传递一个命令并基本执行该命令来工作。例如,在wrapperFunction打电话:

wrapperFunction "xcodebuild -exportArchive -exportFormat IPA -archivePath myApp.xcarchive -exportPath myApp.ipa -exportProvisioningProfile 'myApp adhoc'" 

和wrapperFunction本身:

wrapperFunction() { 
    COMMAND="$1" 
    $COMMAND 
} 

的问题是在'myApp adhoc'单引号,因为通过wrapperFunction运行命令时出现错误:error: no provisioning profile matches ''myApp' 。它不是拿起供应配置文件的全名'myApp adhoc'

编辑:这么说,我也想通过一个可替换的wrapperFunction,这不是要执行的命令的一部分。例如,如果命令失败,我想传递一个字符串来显示。内部包装函数我可以检查$?在命令之后再显示失败字符串if $? -ne 0.我怎样才能传递一个字符串与命令?

回答

3

请勿混淆代码和数据。分别传递参数(这就是sudofind -exec一样):

wrapperFunction() { 
    COMMAND=("[email protected]") # This follows your example, but could 
    "${COMMAND[@]}" # also be written as simply "[email protected]" 
} 

wrapperFunction xcodebuild -exportArchive -exportFormat IPA -archivePath myApp.xcarchive -exportPath myApp.ipa -exportProvisioningProfile 'myApp adhoc' 

要提供自定义错误消息:

wrapperFunction() { 
    error="$1" # get the first argument 
    shift  # then remove it and move the others down 
    if ! "[email protected]" # if command fails 
    then 
     printf "%s: " "$error" # write error message 
     printf "%q " "[email protected]"  # write command, copy-pastable 
     printf "\n"    # line feed 
    fi 
} 
wrapperFunction "Failed to frub the foo" frubber --foo="bar baz" 

这将产生该消息Failed to frub the foo: frubber --foo=bar\ baz

由于引用的方法并不重要,并且不会传递给命令或函数,所以输出可能与此处的引用方式不同。它们仍然功能相同。

+0

完美地工作。非常感谢。仔细阐述它是如何工作的? –

+1

FWIW,第一个例子可以更简单地写成'wrapperFunction(){“$ @”; }'。推测将参数放入数组的原因是在调用封装函数之前允许进行某种操作或检查;这可能值得更加明确。另外,注意在这种包装器中注入可执行文件,特别是如果它们在不安全的环境中运行。 'eval'不是唯一的安全漏洞,尽管它可能是最糟糕的。 – rici

+0

您传入多个参数,然后使用这些参数执行程序。这与试图将多个参数放入一个字符串中相反,将它们解释为shell代码而不是参数,希望能够完整地取回参数。如果你熟悉C,它基本上是'int main(..,char * argv){execve(argv [0],argv,..); }而不是'system(argv [1])'。 –