2013-08-12 29 views
1

一些背景:傳遞引號內的變量的命令在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

嘗試這樣的:

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

或這樣的:

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

第一人給'+ wbemcli GI -nl 'C_PATH:some_class.DeviceID = 「一些設備ID」''和第二一個給出'+ wbemcli gi -nl'C_PATH:some_class.DeviceID ='\''某個設備ID'\'''' – peonicles

+0

@peonicles:這兩個痕跡都可以 - 'wbemcli'命令可以查看單引號或'Some Device ID'周圍的雙引號將整個字符串視爲單個參數,即使'Some Device ID'中有空格也是如此。 'bash'在其他shell的'set -x'下做了不同的迴應,在其他炮彈輸出不明確的地方,其輸出通常是毫不含糊的。 –

+0

ahh好吧,我有一個非常愚蠢的語法錯誤(在$ C_PATH中省略了$)。 #1正在工作完美,謝謝你們! 儘管#2仍然添加了怪異的''''。 – peonicles