← Back to Archives

Script to move a file to a new directory named after its hash

hacks

Someone the other day asked me about a link I sent... I frequently will put stuff up on my webserver and put files in directories named after the hash of the file. This same someone wondered if I had an automated way of doing this... the answer is yup. Below is a bash script that moves a file into a directory named after its hash.

(you can copy this to a file named mvmd5dir, make the file executable (chmod gou+x mvmd5dir) and then move the file to somewhere like /usr/bin/ so that you can just run it from anywhere at the command-line.)

#!/bin/bash # # mvmd5dir (Time-stamp: <2007-09-28 00:20:24 josephhall>) # # This script accepts filenames from the command-line, then # calculates the md5sum hash of the file, creates a directory # named after the md5sum and finally moves the original file # to the new directory. (This script is public domain yo.) # #wrap in a for loop handle multiple files for oldName in "$@" ; do #store the md5sum hash value in a variable #NOTE: the "cut" command extracts the hash value md5print=md5sum ${oldName} | cut -f 1 -d " "

#create the new directory using the hash value mkdir ${md5print}

#mv the file to the new directory mv ${oldName} ${md5print}

#report out to the user what we've done echo just moved ${oldName} to ${md5print}/${oldName} done