wget on failure returns last command executed code unknown

863 Views Asked by At

Here is a small bash code which initially creates a temporary file tmpfile using mktemp followed by a wget operation on success or failure removes the temporary file created.

#!/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

When a right url is passed to the script, wget on success checks the return value of last command using $? and deletes the temporary file as expected.

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

However if a url which result wget a unsuccessful such as 404-not found etc., I assume last executed wget should fail against if check and delete temporary file in else block. This isn't happening as wget just returns without any last return value as shown below. This indeed doesn't delete the temporary file when ever call to wget fails.

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

May I know how to capture every return failure code of wget by any means.

1

There are 1 best solutions below

1
On BEST ANSWER

Question:

May I know how to capture every return failure code of wget by any means.

It should response every return http status code:

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

EDIT: I have tried your code, and it works fine

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

This is the list of exit codes for 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

Check this: Link