我有.sh脚本,除其他外,该脚本从Google获取以下货币汇率:
printf 'Bash: Going to get exchange rates'
echo
wget -qO- "http://www.google.com/finance/converter?a=1&from=usd&to=aud" | sed '/res/!d;s/<[^>]*>//g' > exrates
wget -qO- "http://www.google.com/finance/converter?a=1&from=usd&to=jpy" | sed '/res/!d;s/<[^>]*>//g' >> exrates
wget -qO- "http://www.google.com/finance/converter?a=1&from=usd&to=hkd" | sed '/res/!d;s/<[^>]*>//g' >> exrates
wget -qO- "http://www.google.com/finance/converter?a=1&from=usd&to=nzd" | sed '/res/!d;s/<[^>]*>//g' >> exrates
wget -qO- "http://www.google.com/finance/converter?a=1&from=usd&to=eur" | sed '/res/!d;s/<[^>]*>//g' >> exrates
wget -qO- "http://www.google.com/finance/converter?a=1&from=usd&to=gbp" | sed '/res/!d;s/<[^>]*>//g' >> exrates
mv /home/stan/perl/2014/scripts/exrates /home/stan/perl/2014/exrates/exrates
printf 'Bash: Got exchange rates'
echo
Run Code Online (Sandbox Code Playgroud)
但是,有时脚本会挂在这里。我不介意每次运行时都不更新这些速率,如果挂起,我想完全跳过此步骤,但是如何?
我应该在“ if”语句中输入什么内容,以检查wget是否可以迅速获取数据或将永远使用?wget执行中的更多详细信息也不会受到伤害。
顺便说一句,我不知道为什么wget挂了。浏览器可以正常打开这些页面,相同的命令也可以从终端逐行运行。
我认为它挂起是因为您在脚本中向单个主机发送了许多 HTTP 请求。有问题的主机不太喜欢这样,它开始阻止来自您的 IP 地址的请求。
一个简单的解决方法是sleep在请求之间放置一个。您还可以使用一个函数:
getExchangeRates() {
wget -qO- "http://www.google.com/finance/converter?a=1&from=usd&to=$1" | sed '/res/!d;s/<[^>]*>//g' >> exrates
sleep 10 # Adding a 10 second sleep
}
Run Code Online (Sandbox Code Playgroud)
并通过向函数传递参数来调用它:
getExchangeRates aud
Run Code Online (Sandbox Code Playgroud)
该函数还可以针对各种货币在循环中调用:
for currency in aud jpy hkd nzd eur gpb; do
getExchangeRates $currency
done
Run Code Online (Sandbox Code Playgroud)