wget on failure返回上一个命令执行代码未知

时间:2015-10-29 06:15:19

标签: bash wget mktemp

这是一个小的bash代码,最初使用tmpfile创建临时文件mktemp,然后在成功或失败时执行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不成功的网址(例如404-未找到等),我认为上次执行的wget应该在if检查并删除else中的临时文件时失败1}}阻止。这不会发生,因为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的每个返回失败代码。

1 个答案:

答案 0 :(得分: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