【问题标题】:wget on failure returns last command executed code unknownwget on failure 返回最后一个命令执行的代码未知
【发布时间】:2015-10-29 06:15:18
【问题描述】:

这是一个小的 bash 代码,它最初使用 mktemp 创建一个临时文件 tmpfile,然后在成功或失败时执行 wget 操作删除创建的临时文件。

#!/bin/bash -ex
tmpfile="$(mktemp)"
wget -q $1 -O /tmp/temp.txt
if [ $? -eq 0 ] ; then
    echo "wget success"
    rm "${tmpfile}"
else
    echo "wget fail" 
    rm "${tmpfile}"
fi

当一个正确的 url 被传递给脚本时,wget 成功时使用$? 检查最后一个命令的返回值,并按预期删除临时文件。

root@box:/# ./temp.sh www.google.com
++ mktemp
+ tmpkeyfile=/tmp/tmp.83uGY1NH5B
+ wget -q www.google.com -O /tmp/temp.txt
+ '[' 0 -eq 0 ']'
+ echo 'wget success' 
wget success
+ rm /tmp/tmp.83uGY1NH5B

但是,如果导致 wget 不成功的 URL(例如 404-未找到等),我假设最后执行的 wget 应该会因 if 检查并删除 else 块中的临时文件而失败。这不会发生,因为wget 只是返回而没有任何最后的返回值,如下所示。当调用wget 失败时,这确实不会删除临时文件。

root@box:/# ./temp.sh www.googlegoogle.com
++ mktemp
+ tmpkeyfile=/tmp/tmp.pSL7hKyAlz
+ wget -q www.googlegoogle.com -O /tmp/temp.txt
root@box:/#

我可以知道如何以任何方式捕获wget 的每个返回失败代码。

【问题讨论】:

  • shebang 行中的 -e 告诉 bash 如果任何命令返回非零退出代码,则退出脚本。

标签: bash wget mktemp


【解决方案1】:

问题:

我可以知道如何通过任何方法捕获 wget 的每个返回失败代码吗? 意思。

它应该响应每个返回的http状态码:

wget --server-response http://googlegoogle/nx.file 2>&1 | awk '/^  HTTP/{print $2}'

编辑: 我已经试过你的代码,它工作正常

bash -x ./abc.sh www.googlegoogle.com
++ mktemp
+ tmpfile=/tmp/tmp.pwa08vGnjo
+ wget -q www.googlegoogle.com -O /tmp/temp.txt
+ '[' 4 -eq 0 ']'
+ echo 'wget fail'
wget fail
+ rm /tmp/tmp.pwa08vGnjo

这是 wget 的退出代码列表:

0       No problems occurred
1       Generic error code
2       Parse error — for instance, when parsing command-line options, the .wgetrc or .netrc…
3       File I/O error
4       Network failure
5       SSL verification failure
6       Username/password authentication failure
7       Protocol errors
8       Server issued an error response

检查这个:Link

【讨论】:

  • 有了这个,我必须更改我的代码以检查所有可用的 http 状态代码并接听复杂的电话。
猜你喜欢
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-19
  • 2011-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多