US Dollar amount to Bitcoin Dollar amount

I found myself needing to calculate how much Bitcoin I’d get for a certain US dollar amount, and I grew tired of checking websites.  I made a quick and easy bash shell script that takes US dollar amount as parameter, and returns the current bitcoin value per $1 USD along with the amount of Bitcoin the amount of USD given in the parameter would purchase.  The output is as follows:

MBP:~ danlund$ ./scripts/ 200
Current BTC Value per USD: 3796.03
Answer: 200 will currently buy 0.05268600 BTC

Without any further adieu, here’s the script.  Feel free to edit as you wish, I’m just looking to share it.  This will not unfortunately function without a working internet connection since it pulls current BTC data from Coinbase.

if [[ -z $1 ]]; then
echo “Converts USD amount to BTC amount”
echo “$0 <USD amount to convert to BTC>”
exit 1
AMOUNT=`curl -s | sed ‘s/,/\’$’\n/g’ | sed ‘s/{/\’$’\n/g’ | grep amount | sed ‘s/”//g’ | sed ‘s/:/\’$’ /g’ | awk ‘{ print $2 }’`
BTC_PER_DOLLAR=`bc <<< “scale=8;1/${AMOUNT}”`
BTC_QUANTITY=`bc <<< “scale=8;x=${DOLLARS} * ${BTC_PER_DOLLAR}; if(x<1) print 0; x”`
echo “Current BTC Value per USD: ${AMOUNT}”
echo “Answer: ${DOLLARS} will currently buy ${BTC_QUANTITY} BTC”


EDIT August 22nd, 2017:
Of course I found myself wantign to convert Bitcoins to US dollars, so I wrote a script (based on the above one) that does that.  I figured I’d share it, even though it’s relatively simple.  It saves a a bit of time for those that want to use this.

NOTE: This was created using bash & utils on MacOS with OpenSSL 0.9.8zh 14 Jan 2016.  I tested this on Ubuntu 5.2.1 and the version of Openssl (OpenSSL 0.9.8g 19 Oct 2007) was an issue.  I tested on CentOS 7 with a different version of Openssl (OpenSSL 1.0.1e-fips 11 Feb 2013) and there were no issues.

if [[ -z $1 ]]; then
echo “Converts BTC amount to USD amount”
echo “$0 <BTC amount to convert to USD>”
exit 1
BTC_VALUE=`curl -s | sed ‘s/,/\’$’\n/g’ | sed ‘s/{/\’$’\n/g’ | grep amount | sed ‘s/”//g’ | sed ‘s/:/\’$’ /g’ | awk ‘{ print $2 }’`
BTC_PER_DOLLAR=`bc <<< “scale=8;1 / ${BTC_VALUE}”`

USD_QUANTITY=`bc <<< “scale=2;x=${BTC} / ${BTC_PER_DOLLAR}; if(x<1) print 0; x”`
echo “Current USD Value per BTC: ${BTC_VALUE}”
echo “Answer: ${BTC} will currently return ${USD_QUANTITY} Dollars”