#!/bin/bash
printf -v coin '%s' -1 # crypto.sh bitcoin
price() {
# A function that pulls cryptocurrency price data from coingecko
curl -X 'GET' 'https://api.coingecko.com/api/v3/simple/price?ids='"$1"'&vs_currencies=usd' \
-H 'accept: application/json' 2> /dev/null | # sends download data to /dev/null
sed 's/.*usd"://' | # Removes everything before the price
sed 's/..$//' | # Removes back two }}
sed 's/^/\$/' # Adds dollar sign to the front, returns
}
bitcoin=$(price bitcoin)
ethereum=$(price ethereum)
# Checks to see if there is a command line variable and prints to console
if [[ -z $1 ]]; then
echo "bitcoin: ${bitcoin} | ethereum: ${ethereum}"
else
price=$(price $1) # calls function with command line variable
echo "${1}: ${price} | bitcoin: ${bitcoin} | ethereum: ${ethereum}"
fi
h/t Techstructive for the basic idea. I simplified their code by cutting out the I/O and putting the coin as a variable when calling the script, e.g. crypto.sh bitcoin, and formatting it by piping it through sed. Have I mentioned how much I love sed?
Edit: Modified this on August 12, 2021 so it is now a function and prints a portfolio of coins. I track two or three, and it was getting annoying to have to do them each individually. All you need to do to modify it for the coins you are interested in is create a new function call:
cardano=$(price cardano)
Then add that to both the if and else print results.
echo "${1}: ${price} | bitcoin: ${bitcoin} | ethereum: ${ethereum} | cardano: ${cardano}"
also, add a -s flag to curl to suppress the annoying download progress
The 2> /dev/null sends the annoying download progress to /dev/null. When I tried the -s flag directly, it borks the script.
sed ‘s/[^0-9]//g’
That filters out everything that’s not a digit. Much cleaner 😉
Need to account for the period in the price, and multiple digits in either direction from the period. So, this doesn’t work. But, yeah, it could be made cleaner.