2017-02-25 244 views
1

我正在嘗試開發一個腳本,該腳本將在具有OpenWRT的路由器上運行。現在我可以獲得路由器的IP。我只想將其上傳到Firebase。如果我做了以下它被寫入到數據庫:將一個變量傳遞給CURL(Firebase REST API)

curl -X PUT -d '{"IPv4": "192.168.1.1"}' \ 
    'https://name.firebaseio.com/Values.json' 

我想知道的是通過IP值作爲輸入:

var=$(/sbin/ifconfig eth0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}'); 
curl -X PUT -d '{"IPv4": '"${var}"'}' \ 
     'https://name.firebaseio.com/Values.json' 

如果我運行此我得到一個解析錯誤:

{ 
    "error" : "Invalid data; couldn't parse JSON object, array, or value. Perhaps you're using invalid characters in your key names." 
} 

回答

1

如果你把反斜線雙引號圍繞前${var}curl調用將工作:

curl -X PUT -d '{"IPv4": '\"${var}\"'}' \ 
     'https://name.firebaseio.com/Values.json' 

或者更好的,只是把整個-d ARG在雙引號,並使用反斜線雙引號內:

curl -X PUT -d "{\"IPv4\": \"${var}\"}" \ 
     'https://name.firebaseio.com/Values.json' 

相反,它在這個問題格式化的方式,var值獲取發送不帶引號您的JSON:

$ curl --trace-ascii - -X PUT -d '{"IPv4": '"${var}"'}' \ 
     'https://name.firebaseio.com/Values.json' 

== Info: Trying 104.154.130.226... 
== Info: TCP_NODELAY set 
== Info: Connected to name.firebaseio.com (104.154.130.226) port 443 (#0) 
== Info: TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 
== Info: Server certificate: firebaseio.com 
== Info: Server certificate: Google Internet Authority G2 
== Info: Server certificate: GeoTrust Global CA 
=> Send header, 163 bytes (0xa3) 
0000: PUT /Values.json HTTP/1.1 
001b: Host: name.firebaseio.com 
0036: User-Agent: curl/7.51.0 
004f: Accept: */* 
005c: Content-Length: 25 
0070: Content-Type: application/x-www-form-urlencoded 
00a1: 
=> Send data, 25 bytes (0x19) 
0000: {"IPv4": 192.168.111.100} 
       ^^^^^^^^^^^^^^^ 

不帶引號,這是不是值類型的JSON解析器識別(不是字符串,而不是數字,不是一個對象,而不是一個數組,而不是true/false,而不是null),所以解析失敗。