In 2003, I wrote a custom Amazon-like shopping cart script. Back then, my web scraping skills weren’t, ahem, the best they could have been. For the site’s currency conversions, I had a cron job pull down 3 sets of converstions, calculated the average for each currency pair, then stored the result locally for my use.
At the time, I did this hoping that in a worse-case-scenario, a maximum of 2 sources would die in any weekend. Luckily, the sources lasted for the 3 years whilst I was working for that company (and apparently for another two after that). Now, I hear, they are manually updating a static text file… once in a while.
Today, I have no such needs but as always I am constantly looking for new ways to do things, should the need arise. I also needed a simple currency converter for doing small calculations like how much to top up a prepaid credit card by to purchase something from eBay which is listed in another currency.
Full credits to rafacas at commandliners for the inspiration and as he points out, note that the script uses Google Finance’s page.
# 2009 - Rafa Casado - http://bit.ly/bYZwex
# 2010 - Chris Ergatides - http://bit.ly/9XjAUz
if [ $# -lt 2 ]; then
echo -e "\nUsage: $0 currency1 currency2 amount"
echo "Default: $0 GBP EUR 1"
echo "Example 1: $0 USD GBP"
echo "Example 2: $0 GBP USD 42"
echo $@ | tr "[:lower:]" "[:upper:]"
if [ -n "$1" ]; then FROM=$(toUpper "$1"); else FROM=GBP; fi
if [ -n "$2" ]; then TO=$(toUpper "$2"); else TO=EUR; fi
if [ $TO == $FROM ]; then echo 'Nothing to do!'; exit 2; fi
if [ -n "$3" ]; then A=$3; else A=1; fi
RESULT=`wget -nv -O - "$CONVERTER" 2>&1 | \
sed -n -e 's/.*<span class=bld>\(.*\)<\/span>.*/\1/p'`
echo -e "\nResult: $A $FROM = $RESULT\n"
So, let’s say you’ve named the script currency.sh and made it executable with chmod +x, what does the output look like?
#Called without any parameters:
[[email protected] ~/bin]$ ./currency.sh
Usage: /home/chris/bin/currency.sh currency1 currency2 amount
Default: /home/chris/bin/currency.sh GBP EUR 1
Example 1: /home/chris/bin/currency.sh USD GBP
Example 2: /home/chris/bin/currency.sh GBP USD 42
Result: 1 GBP = 1.1387 EUR
#Called with example 1's parameters:
[[email protected] ~/bin]$ ./currency.sh usd gbp
Result: 1 USD = 0.6475 GBP
#Called with example 2's parameters
[[email protected] ~/bin]$ ./currency.sh gbp usd 42
Result: 42 GBP = 64.8606 USD