简体   繁体   English

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

[英]Passing a variable inside quotation marks to a command in bash

Some context : 一些上下文:

I'm attempting to run a command as part of a bash script to poll for system/device data. 我正在尝试将命令作为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'

So this is working ... 所以这正在工作...

    #!/bin/sh

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

    set -x
    wbemcli ein $C_PATH:$CLASS

Unfortunately, it falls apart when I attempt to integrate the quotation marks into the command. 不幸的是,当我尝试将引号集成到命令中时,它崩溃了。 The code executed in the shell is unexpected to me. 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 is adding quotation marks in places I didn't expect. Bash在我没想到的地方加了引号。 It's even enclosing the entire URL portion in single quotation marks. 甚至将整个URL部分都用单引号引起来。 What's going on ? 这是怎么回事 ?

Try like this: 尝试这样:

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

or like this: 或像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM