shell 使用bash获取货币汇率[已关闭]

cigdeys3  于 2023-05-18  发布在  Shell
关注(0)|答案(1)|浏览(113)

**已关闭。**此问题不符合Stack Overflow guidelines。目前不接受答复。

这个问题似乎不是关于a specific programming problem, a software algorithm, or software tools primarily used by programmers的。如果你认为这个问题与another Stack Exchange site的主题有关,你可以留下评论,解释在哪里可以回答这个问题。
去年关闭。
Improve this question
我想显示当前的汇率从货币欧元到美元在命令行中使用bash shell脚本。我在用市场内幕网站。我在某人的博客上看到使用wget命令

wget -qO- https://markets.businessinsider.com/currencies/eur-usd

但是我怎么能只显示价格呢?期望产出(例如当前汇率1.1347)--> 1.1347 $
PS:我不想使用API
任何帮助都将不胜感激

t40tm48m

t40tm48m1#

使用他们的API干净地做到这一点:

#!/usr/bin/env sh

API='https://markets.businessinsider.com/ajax/'

implode() { printf %s "$*";}

ExchangeRate_GetConversionForCurrenciesNumbers() {
  isoCodeForeign=$1
  isoCodeLocal=$2
  amount=$3
  date=$4
  cacheFile="/tmp/$date-$amount-$isoCodeForeign-$isoCodeLocal.json"

  # Check if we have cached the result to avoid front-running the API
  if ! [ -e "$cacheFile" ]; then
    post_vars=$(
      IFS=\& implode \
        "isoCodeForeign=$isoCodeForeign" \
        "isoCodeLocal=$isoCodeLocal" \
        "amount=$amount" \
        "date=$date"
    )

    method='ExchangeRate_GetConversionForCurrenciesNumbers'
    url="$API$method?$post_vars"
    if ! http_code=$(
      curl -s -w '%{http_code}' \
        -H 'Accept: application/json' \
        -X POST "$url" -o "$cacheFile"
    ); then
      printf 'Failed to connect to %s\n' "$API"
      rm -f "$cacheFile"
      return 1
    fi >&2
    if ! [ "$http_code" = '200' ]; then
      printf 'Unexpected http_code=%s from %s:\n' "$http_code" "POST $url"
      cat "$cacheFile"
      echo
      rm -f "$cacheFile"
      return 1
    fi >&2
  fi
  jq -r '.ConvertedAmountFourDigits' "$cacheFile"
}

getRateEURO_USToday() {
  ExchangeRate_GetConversionForCurrenciesNumbers EUR USD 1 "$(date '+%Y-%m-%d')"
}

exchange_rate=$(getRateEURO_USToday) || exit 1
# Set LC_NUMERIC=C because the float format returned is using . as decimal
LC_NUMERIC=C printf 'The exchange rate for EUR to USD today is: %.4f\n' \
  "$exchange_rate"

相关问题