Add a Unique Number while renaming shows another way to do it, where the script checks if a file with the generated name already exists, instead of keeping track of all previously used names itself. (The fileystem does that for you, after all. Also means it lets you rename some files in places which already have other files whose names aren't changing but may conflict.)