Q:

wget - How to skip not found file?

I use wget to download a file from the internet and use -O option to save image with custom filename. Sometimes, the file is not found, returning 404 error code. For example, I run this command:
wget 'http://www.example.com/path/to/image/file01928.jpg' -O myimagefile.jpg

The result is
 root@localhost:~# wget 'http://www.example.com/path/to/image/file01928.jpg' -O myimagefile.jpg
--2015-09-13 23:11:07--  http://www.example.com/path/to/image/file01928.jpg
Resolving www.example.com (www.example.com)... 93.184.216.34, 2606:2800:220:1:248:1893:25c8:1946
Connecting to www.example.com (www.example.com)|93.184.216.34|:80... connected.
HTTP request sent, awaiting response... 404 Not Found
2015-09-13 23:11:07 ERROR 404: Not Found.

Although the file is not found but the file is still saved to my harddrive:
root@localhost:~# ls
myimagefile.jpg

Is there a way to skip / cancel (do not execute command) not found file? What option(s) should I use?

A:

You could perform a HEAD request to see if the resource (image) is there, and if so, then download it.  You can run wget with -S to print the headers, and --spider to check, but not download a resource.
From man wget

  -S
  --server-response
      Print the headers sent by HTTP servers and responses sent by FTP servers.

  --spider
      When invoked with this option, Wget will behave as a Web spider, which means that
      it will not download the pages, just check that they are there.  For example, you
      can use Wget to check your bookmarks:

              wget --spider --force-html -i bookmarks.html

      This feature needs much more work for Wget to get close to the functionality of
      real web spiders.

Here is an example:
#!/bin/bash

URL='http://www.google.com'
echo "Checking $URL"
if wget -S --spider $URL 2>&1 | grep -q 'Remote file exists'; then
    echo "Found $URL, going to fetch it"
    wget $URL -O google.html;
else
    echo 'Url $URL does not exist!'
fi

URL='http://www.example.com/path/to/image/file01928.jpg'
echo "Checking $URL"
if wget -S --spider $URL 2>&1 | grep -q 'Remote file exists'; then
    echo "Found $URL, going to fetch it"
    wget $URL -O myimagefile.jpg;
else
    echo "Url $URL does not exist!"
fi

Output
Checking http://www.google.com
Found http://www.google.com, going to fetch it
--2015-09-14 05:26:34--  http://www.google.com/
Resolving www.google.com (www.google.com)... 74.125.239.144, 74.125.239.145, 74.125.239.146, ...
Connecting to www.google.com (www.google.com)|74.125.239.144|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: ‘google.html’

    [ <=>                                                    ] 18,684      --.-K/s   in 0.001s

2015-09-14 05:26:34 (13.9 MB/s) - ‘google.html’ saved [18684]

Checking http://www.example.com/path/to/image/file01928.jpg
Url http://www.example.com/path/to/image/file01928.jpg does not exist!

