When using more than 1 IF statement, is there a special guideline that should be followed? Should they be grouped? Should I use parenthesis to wrap the command(s)?
An example to use would be:
IF EXIST somefile.txt IF EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt
There is no “standard” way to do batch files, because the vast majority of their authors and maintainers either don’t understand programming concepts, or they think they don’t apply to batch files.
But I am a programmer. I’m used to compiling, and I’m used to debuggers. Batch files aren’t compiled, and you can’t run them through a debugger, so they make me nervous. I suggest you be extra strict on what you write, so you can be very sure it will do what you think it does.
There are some coding standards that say: If you write an
ifstatement, you must use braces, even if you don’t have anelseclause. This saves you from subtle, hard-to-debug problems, and is unambiguously readable. I see no reason you couldn’t apply this reasoning to batch files.Let’s take a look at your code.
And the
IFsyntax, from the command,HELP IF:So you are chaining
IF‘s as commands.If you use the common coding-standard rule I mentioned above, you would always want to use parens. Here is how you would do so for your example code:
Make sure you cleanly format, and do some form of indentation. You do it in code, and you should do it in your batch scripts.
Also, you should also get in the habit of always quoting your file names, and getting the quoting right. There is some verbiage under
HELP FORandHELP SETthat will help you with removing extra quotes when re-quoting strings.Edit
From your comments, and re-reading your original question, it seems like you want to build a comma separated list of files that exist. For this case, you could simply use a bunch of
if/elsestatements, but that would result in a bunch of duplicated logic, and would not be at all clean if you had more than two files.A better way is to write a sub-routine that checks for a single file’s existence, and appends to a variable if the file specified exists. Then just call that subroutine for each file you want to check for: