Bash:检查json响应并在字符串存在时写入文件

时间:2016-04-29 15:05:04

标签: json bash curl jq

我卷曲json响应的端点并将响应写入文件。 到目前为止,我有一个脚本:

1)。如果文件不存在则卷曲 2)。 else设置一个变量

#!/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次,直到响应包含$ instance

(3)。响应包含$ instance

后写入文件

(4)。正确完成上述操作后,设置变量instance_info = $(cat $ {json_response_file})。

我这样开始......然后被卡住了......

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

1 个答案:

答案 0 :(得分: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; }