首页 文章

如何在Bash for循环中同时访问curl请求的两个数组索引?

提问于
浏览
0

在Bash中,我正在尝试从http://free.currencyconverterapi.com/api/v5/convert?q=USD_GBP查询国家/地区货币并自动更新我的OpenEdge API而无需对符号进行硬编码 . 这意味着我必须在数组中卷曲并保存我的API中的货币符号并卷曲并保存货币转换器API中的值 . 之后我想同时运行两个for循环或同时访问两个数组的索引,以便运行需要的API调用

url/rest/USD/12

一种输入 .

在bash中我称之为回归的卷曲

ZAR USD EUR BWP CHF GBP

来自我的API在一行 . 然后我将结果保存在一个名为currency的变量中

jsonEnd="_ZAR.val"
symbolEnd="_ZAR"

然后我跑了

values=()
for j in ${currency[*]};
do
        ${values[j]}=$(curl -X GET -H "Content-type: application/json" http://free.currencyconverterapi.com/api/v5/convert?q=${currency[j]}$symbolEnd&compact=y | jq '.${currency[j]}$jsonEnd')         
done

要将货币值放入一个数组中,其中'_ZAR.val'来自json结果,尝试用jq指向“val”

{
"USD_ZAR": {
    "val": 14.23065
} }

最后我试图运行一个POST Curl,它需要上面找到的相对货币符号,如USD,并且要更新一个值 . 以这种形式

curl -X PUT -H "Content-Type: application/json" -H "Authorization: $context" http://192.168.xxx.xxx:8080/rest/exchangerates/USD/12

我试过这个

for i in ${values[@]}
do    
      curl -X PUT -H "Content-Type: application/json" -H "Authorization: $context" http://192.168.xxx.xxx:8080/rest/exchangerates/${currency[i]}/${values[i]}
done

我无法做到,错误包括

curl: (6) Could not resolve host: USD_ZAR

等我是bash的新手

1 回答

  • 1

    ${currency[*]}${currency[*]} 都将扩展为数组内的值 . 所以当你写...

    for j in "${currency[@]}"; do
        echo "${currency[j]}"         
    done
    

    ...你不会访问 ${currency[0]}${currency[USD]} 这样的东西不存在 .

    另外,要分配变量,您不能写 ${array[i]}=value 但必须使用 array[$i]=value .

    您可能还希望切换到关联数组(也称为字典或映射),您可以在其中使用字符串作为索引 . 这是一个粗略的骨架:

    currencies=(ZAR USD EUR BWP CHF GBP)
    declare -A values
    for c in "${currencies[@]}"; do
        values["$c"]="$(curl ..."$c"... | jq ..."$c"... )"
    done
    
    c=EUR
    echo "The value of $c is ${values[$c]}"
    

相关问题