Currency Conversion on Bash

Currency.sh

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:

currency.sh   [quantity]

You currency code must meet ISO 4217 standard.

Script:

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

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

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

unit_price_f=$(curl -s "https://free.currencyconverterapi.com/api/v5/convert?q=${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
  echo -n "$3 $1 is "
  echo "$3 * $unit_price" | bc -l | tr -d "\n"
  echo " $2"
fi

Join the conversation

1 Comment

Leave a comment

Leave a Reply

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