Currency Conversion on Bash

I had an idea long ago to convert currency on bash.

So first you need a live currency conversion API in order to get a most up-to-date conversion rate data, preferably free. After searching through the internet, this one is a good API. I’ve been using it for some time and normally it is quite stable.

The only dependency you need to install is jq, please use your package manager to install.

Usage:   [quantity]

You currency code must meet ISO 4217 standard.


jq 2> /dev/null
if [ "$?" != 2 ]; then
  echo "Please install jq"
  exit 1

if [ -z "$1" -o -z "$2" ]; then
  echo "Please provide first and second currency."
  echo "e.g. $0 CAD USD [amount]"
  exit 1

currency1=`echo -n $1 | tr '[:lower:]' '[:upper:]'`
currency2=`echo -n $2 | tr '[:lower:]' '[:upper:]'`

unit_price_f=$(curl -s "${currency1}_${currency2}&compact=y" | jq ".${currency1}_${currency2}.val")

unit_price=$(printf "%.8f" $unit_price_f)

echo Unit price buy $1 from $2 is $unit_price.

if [ ! -z "$3" ]; then
  echo -n "$3 $1 is "
  echo "$3 * $unit_price" | bc -l | tr -d "\n"
  echo " $2"

Most updated version will be living in my git

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.