将引号内的变量传递给bash中的命令

时间:2013-08-12 11:19:20

标签: linux bash

某些背景信息:

我正在尝试运行命令作为bash脚本的一部分来轮询系统/设备数据。

# Recommended usage in the command line, contains single and double quotes
wbemcli ein 'http://localhost:5988/root/cimv2:some_class'
wbemcli gi 'http://localhost:5988/root/cimv2:some_class.DeviceID="Some Device ID"'

# I can get away with just 1 level of quotation marks
wbemcli ein http://localhost:5988/root/cimv2:some_class
wbemcli gi http://localhost:5988/root/cimv2:some_class.DeviceID="Some Device ID"
wbemcli gi http://localhost:5988/root/cimv2:some_class.DeviceID='Some Device ID'

所以这是有效的......

    #!/bin/sh

    C_PATH=http://localhost:5988/root/cimv2
    CLASS=some_class
    ID="Some Device ID"

    set -x
    wbemcli ein $C_PATH:$CLASS

不幸的是,当我尝试将引号集成到命令中时,它就崩溃了。在shell中执行的代码对我来说是意料之外的。

    # Code
    wbemcli gi $C_PATH:$CLASS.DeviceID=\"$ID\"

    output $ ./myscript
    + wbemcli gi 'http://localhost:5988/root/cimv2:some_class.DeviceID="Some' Device 'ID"'

    # I was expecting this ...
    output $ ./myscript
    + wbemcli gi http://localhost:5988/root/cimv2:some_class.DeviceID="Some Device ID"




Bash在我没想到的地方添加了引号。它甚至将整个URL部分用单引号括起来。发生了什么事?

1 个答案:

答案 0 :(得分:1)

试试这样:

wbemcli gi -nl "$C_PATH:$CLASS.DeviceID=\"$ID\""

或者像这样:

wbemcli gi -nl "$C_PATH:$CLASS.DeviceID='$ID'"
相关问题