Command Line Currency Converter with curl and jq (Exact Decimals)
5 min read
A command line currency converter takes about ten lines of Bash: call an exchange-rate API with curl, pull the answer out with jq, and print it. The part people get wrong is the arithmetic. Shell tools like awk and printf use binary floating point, so a money amount can quietly pick up errors in the last digits.
This guide builds a small converter that stays exact. You will see a one-liner, a safer script with error handling, a way to do your own math with bc, and a freshness check you can run from cron. The examples use the GetRatesAPI convert endpoint, but the patterns apply to any JSON rate API.
The one-line version
Create an API key in the dashboard and export it, so it never lands in your shell history or a script file:
export GETRATES_API_KEY="YOUR_API_KEY"
Then ask the API to convert 125.50 USD to EUR:
curl -s "https://api.getratesapi.com/v1/convert?from=USD&to=EUR&amount=125.50" \
-H "Authorization: ApiKey $GETRATES_API_KEY" | jq -r '.converted_amount'
The /v1/convert endpoint does the multiplication for you and returns converted_amount as a JSON string. It costs 1 request unit. The result is not rounded, so you decide how many digits to show. Authentication details are in the authentication docs.
Why does jq -r matter here? Because the value is a string, jq passes it through untouched. If an API returned a JSON number instead, some jq versions would convert it to a double and could print a slightly different value than the server sent. Strings avoid that whole class of problem.
Why shell math drifts
Suppose you fetch a rate and multiply it yourself:
# Don't do this for money
awk "BEGIN { print 125.50 * 1.0842 }"
printf "%.2f\n" "$(awk "BEGIN { print 125.50 * 1.0842 }")"
awk parses both numbers as doubles. For small amounts you may never notice, but values such as 0.1 and 0.2 cannot be represented exactly in binary, and rounding with printf "%.2f" can land on the wrong cent for half-way cases. The same applies to tiny crypto prices with many decimals. For more on this, see currency conversion rounding without floating-point errors.
There are two safe options in a shell:
- Let the API do the multiplication with
/v1/convert. - Fetch the rate string and multiply with
bc, which does arbitrary-precision decimal arithmetic.
A safer script with error handling
A script you rely on should check the HTTP status, read the error code, and fail with a useful message. Save this as convert.sh:
#!/usr/bin/env bash
set -euo pipefail
: "${GETRATES_API_KEY:?Set GETRATES_API_KEY first}"
if [ "$#" -ne 3 ]; then
echo "usage: $0 AMOUNT FROM TO (example: $0 125.50 USD EUR)" >&2
exit 2
fi
amount="$1"
from="$2"
to="$3"
# Capture body and HTTP status in one request
raw=$(curl -sS --get "https://api.getratesapi.com/v1/convert" \
--data-urlencode "from=$from" \
--data-urlencode "to=$to" \
--data-urlencode "amount=$amount" \
-H "Authorization: ApiKey $GETRATES_API_KEY" \
-w $'\n%{http_code}')
status="${raw##*$'\n'}"
body="${raw%$'\n'*}"
if [ "$status" != "200" ]; then
code=$(echo "$body" | jq -r '.code // "unknown"')
case "$code" in
invalid_asset_symbol) echo "Unknown currency code: $from or $to" >&2 ;;
invalid_amount) echo "Not a valid amount: $amount" >&2 ;;
unsupported_pair) echo "No rate available for $from to $to" >&2 ;;
rate_limit_exceeded)
wait=$(echo "$body" | jq -r '.retry_after_seconds // 1')
echo "Rate limited, retry in ${wait}s" >&2 ;;
quota_exceeded) echo "Monthly quota used up" >&2 ;;
unauthorized) echo "Check GETRATES_API_KEY" >&2 ;;
*) echo "API error: $code (HTTP $status)" >&2 ;;
esac
exit 1
fi
echo "$body" | jq -r '.converted_amount'
Make it executable and run it:
chmod +x convert.sh
./convert.sh 125.50 USD EUR
A few details are worth noting:
--data-urlencodewith--getbuilds the query string safely, so odd input cannot break the URL.-sShides the progress meter but still prints curl-level failures such as DNS errors.- The script branches on the error
code, not on the message text, because messages can change. The full list is in the error reference. - Malformed requests and rate-limited requests are not billed, so a typo in a loop does not eat your quota.
Prefer exit codes you can test: 0 for success, 1 for an API problem, 2 for bad usage. That makes the script easy to chain with && or use in CI.
Doing your own math with bc
Sometimes you need the rate itself, for example to apply a margin, convert many amounts, or store the rate with a record. Fetch it with /v1/rates/{base}/{quote}:
rate_json=$(curl -sS "https://api.getratesapi.com/v1/rates/EUR/USD" \
-H "Authorization: ApiKey $GETRATES_API_KEY")
rate=$(echo "$rate_json" | jq -r '.rate')
echo "$rate_json" | jq -c '{rate, as_of, status, type}'
An example response looks like this (the numbers are illustrative):
{"base":"EUR","quote":"USD","rate":"1.0842","as_of":"2026-01-02T10:00:00Z","status":"fresh","type":"direct"}
Now multiply with bc, then round half up to two decimals:
amount="125.50"
product=$(echo "scale=10; $amount * $rate" | bc)
# Round half up to 2 decimals (positive amounts only)
rounded=$(echo "scale=2; ($product + 0.005) / 1" | bc)
echo "$rounded"
bc truncates to the scale you set, so you carry extra digits through the multiplication and round once at the end. The + 0.005 trick works for positive amounts. For zero-decimal currencies such as JPY, add 0.5 and use scale=0. How many digits each currency needs is covered in currency decimal places and minor units.
If you want a result as JSON for another tool, build it with jq --arg, which keeps values as strings:
jq -n --arg amount "$rounded" --arg currency "USD" \
'{amount: $amount, currency: $currency}'
Avoid --argjson or bare numbers for money, since they turn the value back into a number.
Check freshness before you trust a rate
Every rate carries as_of and a status of fresh or stale. Stale rates are flagged, not withheld, so a script that needs current data should look at the flag itself:
if ! echo "$rate_json" | jq -e '.status == "fresh"' > /dev/null; then
echo "Warning: rate is stale (as_of $(echo "$rate_json" | jq -r .as_of))" >&2
fi
jq -e sets its exit code from the result, which makes it handy in if statements. Also remember that a derived rate, one computed through USD, EUR or BTC when no market quotes the pair directly, reports the as_of of its oldest input. For background, read cross rates explained.
Running it from cron
A common use is a daily rate log or a threshold alert. A crontab line might look like this:
# Every day at 08:00, append a USD to EUR conversion to a log
0 8 * * * GETRATES_API_KEY=YOUR_API_KEY /home/me/convert.sh 1000 USD EUR >> /home/me/usd-eur.log 2>&1
Two cautions:
- Cron does not load your shell profile, so set the key explicitly or read it from a file with restricted permissions (
chmod 600). - This records your own observations over time. It is not a historical rates feed, and GetRatesAPI does not offer historical data, so log what you need when you need it.
Keep an eye on volume if you loop over many pairs. One call to /v1/rates/USD?quote=EUR,GBP,JPY returns up to 20 quotes against a single base for 1 request unit, which is far cheaper than 20 separate calls. See getting multiple exchange rates in one API call. If you do hit a 429, wait the number of seconds in retry_after_seconds, as described in the rate limit docs.
Summary and next step
For a reliable command line currency converter:
- Use
/v1/convertwhen you only need the converted amount. - Treat rates and amounts as strings; use
bcinstead ofawkorprintffor math. - Round once, at the end, to the currency's decimal places.
- Branch on the error
codeand checkstatuswhen freshness matters. - Keep the API key in an environment variable.
You can sign up for the free plan with no credit card, try the calls in the dashboard playground, and paste the script above into your own tooling. Plan limits are listed on the pricing page.