How can I make a download an image, md5 hash the image, and save that image with the md5 hash as name to a directory using wget?

# An example of the image link...

# Save the image linked with for name the MD5 hash


# Save the image with the new name to another directory


You can do it in different ways. A little script will help. You can call it with /bin/bash myscript.sh http://yourhost/yourimage.ext where_to_save. The destination directory is an optional:

DestDir=${2:-"~/Users/TheGrayFox/Images/"}   # fix destination directory
MyPath=$(dirname $MyLink)                    # strip the dirname  (Not used)
MyFile=$(basename $MyLink)                   # strip the filename
Extension="${MyFile##*.}"                    # strip the extension 

wget $MyLink                                 # get the file
MyMd5=$(md5sum $MyFile | awk '{print $1}')   # calculate md5sum
mv $MyFile  ${DestDir}/${MyMd5}.${Extension} # mv and rename the file
echo $MyMd5                                  # print the md5sum if wanted

The command dirname strips last component from file name, and the command basename strips directory and suffix from filenames.

You can even decide to save directly the file from wget in the destination directory and after to calculate the md5sum and rename it. In this case you need to use wget From_where/what.jpg -O destpath. Note is a capital o O and not a zero.

  • Appreciate the explanation, thanks! Some image files contain *.png extensions. On a Mac, md5 is equivalent to our md5sum.
    – TheGrayFox
    Jul 19 '14 at 0:40

That's a little complex for wget to do, since its sole purpose is to just pull stuff from the intarwebs. You will likely have to shuffle things around a bit.

$ wget -O tmp.jpg http://31.media.tumblr.com/e1b8907c78b46099fd9611c2ab4b69ef/tumblr_n8rul3oJO91txb5tdo1_500.jpg; mv tmp.jpg $(md5sum tmp.jpg | cut -d' ' -f1).jpg
$ ls *jpg

Since that's a bit obnoxious to copypasta all the time, you can just make a shell script and call it with "./fetch.sh http://example.com/image.jpg"

$ cat fetch.sh 
#! /bin/bash

wget -O /tmp/tmp.fetch $url
sum=$(md5sum /tmp/tmp.fetch | cut -d' ' -f1)
mv /tmp/tmp.fetch ${HOME}/Images/${sum}.${ext}

I did a quick edit to make the above work for all file types, not just jpg.

  • No problem. If you're using a Mac, I'm not 100% sure if the above will work. I could only test that out on a Linux box.
    – Falsenames
    Jul 19 '14 at 1:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.