shell 如何在循环中处理curl请求

lnvxswe2  于 2023-03-19  发布在  Shell
关注(0)|答案(2)|浏览(364)

我的bash脚本在循环中发送curl请求,第一次迭代工作正常,但是第二次出现了curl: (6) Could not resolve host:key1, Error: Process completed with exit code 6.这样的错误
我的代码看起来像

IFS=',' read -ra keys <<< "key1, key2, key3, key4, key5"
for key in "${keys[@]}"
do
  echo "Deleting cache for key: $key"
  response=$(curl -X DELETE \
                  -H "Accept: application/vnd.github+json" \
                  -H "Authorization: Bearer GITHUB_TOKEN"\
                  -H "X-GitHub-Api-Version: 2022-11-28" \
                  https://api.github.com/repos/OWNER/REPOSITORY/actions/caches?key=$key)
  if [ $? -ne 0 ]; then
    echo "Error occurred while deleting key $key"
    continue
  fi
  echo "Response for key $key: $response"
done

如何解决此问题

wgeznvg7

wgeznvg71#

声明数组的方式是错误的,请检查:

IFS=',' read -ra keys <<< "key1, key2, key3, key4, key5"
echo "[${keys[1]}]"
[ key2]

您的键中有多余的前导空格。因此:

IFS=',' read -ra keys <<< "key1, key2, key3, key4, key5"
for key in "${keys[@]}"; do
  key="${key// /}"
  echo "Deleting cache for key: "
  response=$(curl -X DELETE \
    -H "Accept: application/vnd.github+json" \
    -H "Authorization: Bearer GITHUB_TOKEN"\
    -H "X-GitHub-Api-Version: 2022-11-28" \
    https://api.github.com/repos/OWNER/REPOSITORY/actions/caches?key=$key)
  if [ $? -ne 0 ]; then
    echo "Error occurred while deleting key $key"
    continue
  fi
  echo "Response for key $key: $response"
done

这里,key="${key// /}"修剪空格,使用shell简单 * 参数扩展 *
请参见:http://mywiki.wooledge.org/BashFAQ/073
LESS='+/Parameter Expansion' man bash
另请参见http://wiki.bash-hackers.org/syntax/pe

vxbzzdmp

vxbzzdmp2#

您的列表/数组在每个KEY前面引入了一个空格....请尝试清除空格(请参阅代码中的注解):

IFS=',' read -ra keys <<< "key1, key2, key3, key4, key5"
for key in "${keys[@]}"
do
  key="${key// /}"
  echo "Deleting cache for key: $key"
  response=$(curl -X DELETE \
                  -H "Accept: application/vnd.github+json" \
                  -H "Authorization: Bearer GITHUB_TOKEN"\
                  -H "X-GitHub-Api-Version: 2022-11-28" \
                  https://api.github.com/repos/OWNER/REPOSITORY/actions/caches?key=$key)
  if [ $? -ne 0 ]; then
    echo "Error occurred while deleting key $key"
    continue
  fi
  echo "Response for key $key: $response"
done

相关问题