2016-04-29 57 views
0

我爲json響應蜷縮一個端點並將響應寫入文件。 到目前爲止,我已經得到了一個腳本:Bash:如果字符串存在,請檢查json響應並寫入文件

1)。如果該文件不存在,則執行卷曲操作並且2)。否則設置變量

#!/bin/bash 
instance="server1" 
curl=$(curl -sk https://my-app-api.com | python -m json.tool) 
json_response_file="/tmp/file" 

if [ ! -f ${json_response_file} ] ; then 
    ${curl} > ${json_response_file} 
    instance_info=$(cat ${json_response_file}) 
else 
    instance_info=$(cat ${json_response_file}) 
fi 

問題是,該文件可能存在響應錯誤或爲空。 可能使用bash直到,我想

(1)。檢查(使用JQ)curl響應中的字段包含$ instance,然後才寫入該文件。

(2)。重試卷曲XX次,直到響應包含$實例

(3)。寫入文件一旦響應包含$實例

(4)。當上述操作正確完成時,設置變量instance_info = $(cat $ {json_response_file})。

我開始喜歡這個......然後就死......

until [[ $(/usr/bin/jq --raw-output '.server' <<< ${curl}) = $instance ]] 
do 
+0

做你的條件無法工作,或者這是一個問題搞清楚如何實現邏輯? –

+0

爲什麼你需要'python -m json.tool'當你有'jq'? –

+0

它試圖找出邏輯的問題。我真的不需要python -m json.tool。 – Narrabit10

回答

0

一個理智的實現可能是這個樣子:

retries=10 
instance=server1 
response_file=filename 

# define a function, since you want to run this code multiple times 
# the old version only ran curl once and reused that result 
fetch() { curl -sk https://my-app-api.com; } 

instance_info= 
for ((retries_left=retries; retries_left > 0; retries_left--)); do 
    content=$(fetch) 
    server=$(jq --raw-output '.server' <<<"$content") 
    if [[ $server = "$instance" ]]; then 
    # Writing isn't atomic, but renaming is; doing it this way makes sure that no 
    # incomplete response will ever exist in response_file. If working in a directory 
    # like /tmp where others users may have write, use $(mktemp) to create a tempfile with 
    # a random name to avoid security risk. 
    printf '%s\n' "$content" >"$response_file.tmp" \ 
     && mv "$response_file.tmp" "$response_file" 
    instance_info=$content 
    break 
    fi 
done 
[[ $instance_info ]] || { echo "ERROR: Giving up after $retries retries" >&2; } 
+0

謝謝 - 那是一種享受。現在,我將離開,並確保我瞭解您的代碼。再次感謝 – Narrabit10

+0

隨時詢問您是否有任何問題 - 我可以爲此處使用的大多數實踐提供參考。例如,函數封裝在BashFAQ#50中進行了介紹:http://mywiki.wooledge.org/BashFAQ/050 –

+0

...其他一些函數,比如在處理外部提供的時候更喜歡'printf'而不是'echo'數據有點兒模糊 - 如果好奇的話,請參閱POSIX規範的APPLICATION USAGE部分中的'echo',http://pubs.opengroup.org/onlinepubs/009604599/utilities/echo.html。 –

相關問題