"Do you want the "latest file" as per the filesystem or the highest-sequence file as per your naming convention? Is the inode change time important? The modification time? Is it just the filename? What if the files get out of sync and you end up having S0007 but not S0006? Do you want to still delete S0005 if it exists? Why not sort your files, pop the two newest off the array, then delete the rest if making sure you have the two newest available is what you're actually trying to do?"
Sorting the files and popping the two newest off the array does sound like a good idea but I'll have to think about it and see if it works for my case. Thank you for the recommendation.
I thought about this and I think the best way to proceed in my case will be to look for a file with the biggest number (S0007 over S0005 for example), then look if the previous one is there, remove the previous one and proceed to create the next one. So if 7 is there, check if 6 is there, delete 6 and proceed to create 8. I'll have to think about the rest of my script and read up a tutorial to figure out my other issues, but if I can get past the thing that I just described it would be great. Can someone help me regarding how I can do that within my $step variable? How can I say "if we are at step x, check step x-1 exists and create step x+1"?