Bash Prepend Random Number to Filename

December 24, 2014

I recently bought a NIX 7 Inch Hu-Motion Digital Photo Frame – X07E for a christmas gift. I was very pleased with the purchase, minus one annoying flaw. The “random sequence” setting would go back to the same photo about a third of the time. I came up with this script as a simple fix.

#!/bin/bash
#
# FILE: 
#   prepend_random_num.sh
# ABOUT: 
#   Prepends a random number between 1-65000 and an underscore to all files of specified type
#   Runs on Mac OSX & Linux
# EXAMPLE: 
#   $ ls 
#   a.jpg    b.jpg
#   $ sh prepend_random_num.sh jpg
#   $ ls
#   138_b.jpg    8474_a.jpg    

for file in *.$1
do
  rand=$(jot -r 1 1 65000 || shuf -i 1-65000 -n 1)
  mv "$file" "$rand"_"$file"
done