I had a bunch of folders with some old photos, and I needed to randomize the filenames as an easy way to get a random selection of files. This should’ve been easy, but I made the mistake of googling the answer instead of writing this one-liner myself because I felt lazy.

Google returns hundreds of hits, and almost every discussion is replete with bad code and dumb suggestions. I saw one “answer” where the guy proposed an example that would’ve renamed all your files using the same name, effectively deleting everything. Another sample code removed the file extensions.

So here’s my take on this apparently not-so-trivial task:

find . -maxdepth 1 -mindepth 1 -type f \
-regextype posix-extended -regex '^.*\.([jpegJPEG]{3,4})$' | while read f
do 
  /bin/mv "${f}" "$(echo "${f}" | sha1sum | cut -f1 -d' ').${f##*.}"
done

And here’s another option that uses uuidgenthat would address any issues arising from the deterministic nature of the SHA-1 hash and the tiny chance of a filename collision:

find . -maxdepth 1 -mindepth 1 -type f \
-regextype posix-extended -regex '^.*\.([jpegJPEG]{3,4})$' | while read f
do 
  /bin/mv "${f}" "$(uuidgen).${f##*.}"
done