Skip to content

Instantly share code, notes, and snippets.

@Pigpog
Created April 25, 2021 05:46
Show Gist options
  • Save Pigpog/cf46b88aadf19b9ae8694bc68cf8eec8 to your computer and use it in GitHub Desktop.
Save Pigpog/cf46b88aadf19b9ae8694bc68cf8eec8 to your computer and use it in GitHub Desktop.
Simple UNIX shell script for currency conversion
#!/bin/sh
[ -z $2 ] || [ ! -z $4 ] && echo "Usage: currconv FROM TO [AMOUNT]" && exit;
# Parameters must be uppercase
FROM=$(echo $1 | tr 'a-z' 'A-Z' );
TO=$(echo $2 | tr 'a-z' 'A-Z' );
# SAMPLE: {"base":"CAD","rates":{"USD":0.8010888328},"date":"2021-04-23"}
RESPONSE="$(curl -s --http2 "https://api.ratesapi.io/api/latest?base=$FROM&symbols=$TO")";
# Check for API errors
echo $RESPONSE | grep -s "error" && echo "API error: $RESPONSE" && exit;
# Extract rate from response
RATE=$(echo $RESPONSE | cut -f4 -d\: | cut -f1 -d\} );
# If no amount given, output the rate
[ -z $3 ] && echo "Rate between $FROM and $TO: $RATE" && exit;
# Output amount * rate
echo "$3 $FROM is worth $(echo "$RATE*$3" | bc) $TO";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment