8

Tip #821   Command line currency conversion

The script below can be used to convert between different currencies on the command line. In order to use the script, you would enter something like "[scriptname] 150 USD GBP" to give the value of 150 US dollars in British pounds.

Supported currencies are Euro, U.S. dollar British pound, Japanese yen, Swiss franc, Canadian dollar, Australian dollar, and Indian rupee.

#!/bin/bash

toUpper() { echo $@ | tr "[:lower:]" "[:upper:]"; }

if [ $# -eq 2 ]
then
  NUM=1;CURRENCY1=$(toUpper "$1"); CURRENCY2=$(toUpper "$2")
elif [ $# -eq 3 ]
then
  NUM=$1;CURRENCY1=$(toUpper "$2"); CURRENCY2=$(toUpper "$3")
else
  echo "Usage: $0 [number] currency1 currency2"
  echo "Ex: $0 100 EUR USD"
  echo "Available currencies: EUR, USD, GBP, JPY, CHF, CAD, AUD, INR"
  exit 1
fi

CONVERSION=`wget -nv -O - "http://finance.google.com/finance?q=$CURRENCY1$CURRENCY2" 2>&1 | \
        grep " 1 $CURRENCY1 " | \
        sed -e "s/^.*<span class=bld>&nbsp;\(.*\)&nbsp;$CURRENCY2.*$/\1/"`

if [ ${CONVERSION:-1} == "1" ]
then
  echo "Network error"
else
  RESULT=$(echo $CONVERSION \* $NUM | bc)
  echo "$NUM $CURRENCY1 = $RESULT $CURRENCY2"
fi

exit 0