Kosher Coding

Don't ask. Basically, I was writing another Bash script (surprise!) at work, and came across something that is sitting uneasy with me. And the only reason I can think of, is it isn't "Kosher". Let me explain.

The Bash shell, as we all know, is case sensitive. What happens when I have a script that depends on a file being all lowercase, and a file that can be either all uppercase, or all lowercase? The file will be one or the other here at work. Here's what an employee suggested for handling such a situation:

The script will execute and run as normal. If SAMPLE.FIN does not exist, it will simply output an error saying so, and continue running through the script. For some reason, this really bothers me. Again, it just doesn't seem to be "Kosher", or proper coding practice. The code below would seem to be better:

This seems to be a bit better, doesn't it? After all, as I said earlier, the file will be in one of two cases: either all uppercase, or all lowercase. But even at that, the script is relying on the fact that the file MUST be in lowercase to continue. This means not only is case important, but existence too. The file must exist. This is easy with simple logic:

Now, what if for some unforeseen reason, one or more letters in the file name are not lowercase? EG: Sample.fin, or sample.FIN. Then what? Well the best I can come up with is regex (thanks to Steve for helping me with this):

This handles both the existence of the file, and any case of any letter in the file name, as long as the file name is 'sample.fin'. Now, an error won't output if the file does not exist because of case. Also, our script won't continue if the file is nonexistent. The only thing that still bothers me about this code is moving the same file to itself:

1

mv sample.fin sample.fin

Although no error will be output, it seems just silly. However, we can fix this with another if statement:

This seems like a lot of work just to rename a simple file from one case format to another. In the example above, I have taken into account the existence of the file. If it exists, continue, otherwise exit the function. I have also taken into account any case representation of the file name. If the file name is in all lowercase, move on, otherwise rename it to all lowercase.

So there you have it. Kosher Code. I don't know how else to explain it other than avoiding redundant and error-prone code as well as testing ALL cases.