How do I nest a variable that is a string inside of another variable that is a saved output of a command?
I want to accomplish what this code does:
xmrprice=$(curl -s 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cbitcoin-cash%2Clitecoin%2Cmonero&vs_currencies=usd&include_market_cap=true' |jq -r '.monero'|jq -r '.usd')
echo "The price of Monero is $xmrprice"
btcprice=$(curl -s 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cbitcoin-cash%2Clitecoin%2Cmonero&vs_currencies=usd&include_market_cap=true' |jq -r '.bitcoin'|jq -r '.usd')
echo "The price of BTC is $btcprice"
ltcprice=$(curl -s 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cbitcoin-cash%2Clitecoin%2Cmonero&vs_currencies=usd&include_market_cap=true' |jq -r '.litecoin'|jq -r '.usd')
echo "The price of Litecoin is $ltcprice"
but without calling curl
three times. Removing the -s
flag would demonstrate that curl is indeed called three times. I want to assign the string from the output of
curl -s https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cbitcoin-cash%2Clitecoin%2Cmonero&vs_currencies=usd&include_market_cap=true
to a variable and then extract from it the values of xmrprice
, brcprice
, and ltcprice
.
Much like this Python code does it:
#!/usr/bin/python3
#pip3 install requests
import requests
import json
result = requests.get("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cbitcoin-cash%2Clitecoin%2Cmonero&vs_currencies=usd&include_market_cap=true", headers = {"accept":"application/json"})
print("Monero's and Bitcoin's prices as of now:")
print(str(result.json()["monero"]["usd"]))
print(str(result.json()["bitcoin"]["usd"]))
I have come across this question on nesting variables in Bash but it relates more to assigning a nested outputs of multiple commands to a variable.
I've tried all this:
response=$(curl -s https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cbitcoin-cash%2Clitecoin%2Cmonero&vs_currencies=usd&include_market_cap=true)
#xmrprice=(${response}|jq -r '.monero'|jq -r '.usd') #syntax error near unexpected token `|'
#xmrprice=("${response}"|jq -r '.monero'|jq -r '.usd') #syntax error near unexpected token `|'
#xmrprice=$("${response}"|jq -r '.monero'|jq -r '.usd') #{"error":"Missing parameter vs_currencies"}: command not found
#xmrprice=$("{response}"|jq -r '.monero'|jq -r '.usd') #: {response}: command not found
echo "The price of Monero is ${xmrprice}".
None of it works. The comments describe the errors that I got from Bash.