title: bash: Truncate Filenames, keeping them unique
body: <p>I'm using a for-loop similar to this one to truncate all filenames in a folder to 16 characters:</p>
  
  <pre><code>for i in *; do
      Shortname=${i:0:16}     # Let's assume I don't need the extension
      mv "$i" "$Shortname"
  done
  </code></pre>
  
  <p>The problem is: Whenever two filenames have the same first 16 characters, the later one will overwrite the previous one (on OS X mv behaves that way).</p>
  
  <p>How can I check if a file with the name "Shortname" already exists, and if so, replace the last character of "Shortname" with a number. Then check again if a file with that name exists, and if so, try a higher number. And so on. If it arrives at number 9 and so far all names have been taken, it should replace the last TWO characters of the "Shortname" with "10" and check if that file already exists.</p>
  
  <p>Example: Let's say I have a directory with the following files in it:</p>
  
  <pre><code>MyTerriblyLongLongFirstFile.jpg
  MyTerriblyLongLongSecondFile.jpg
  MyTerriblyLongLongThirdFile.jpg
  ...
  MyTerriblyLongLongFourteenthFile.jpg
  ...
  MyTerriblyLongLongOneHundredSixtySeventhFile.jpg
  ...
  MyTerriblyLongLongFiveMillionthFile.jpg
  </code></pre>
  
  <p>Note that the first 16 letters are the same for all files. After running the script, I would like them to be renamed to this:</p>
  
  <pre><code>MyTerriblyLongL1.jpg
  MyTerriblyLongL2.jpg
  MyTerriblyLongL3.jpg
  ...
  MyTerriblyLong14.jpg
  ...
  MyTerriblyLon167.jpg
  ...
  MyTerribl5000000.jpg
  </code></pre>
  
  <p>It doesn't matter if "MyTerriblyLongLongFourteenthFile.jpg" is renamed to "MyTerriblyLong14.jpg", that depends on alphabetical sorting. It's just important that they each get a unique name.</p>
  
  <p>What is the best way to do this?</p>