make two positive statements that do the same things. after all, an "or" statement is 2 branches of logic that leads to a single statement. that single statement can be repeated multiple times with different conditions.
instead of this:
if "%1" == "x" OR "%1" == "X" ECHO Ok
write this:
if "%1" == "x" echo ok
if "%1" == "y" echo ok
Or, if you simply want to ignore case when you compare the strings (as your example suggests), you can use the [tt]/i[/tt] flag on the [tt]if[/tt] command:
I ususally have to use percent at the beginning and at the end of my variable. Also, there can't be a space between the variable and the equals. Maybe I'm doing more than I need to, but just wanted to throw that in there in case you are running into other problems. This is how I would write it...
You're right about the spaces. In some cases, batch files/windows commands do take notice of any spaces between = and variables/strings. The trick is to be consistent with the number of spaces you use.
You should only need to use the second % character if you are referring to environment variables. This is true at the command line and in batch files. For example:
[tt]set mytext=Hello
echo %mytext%[/tt]
However %0, %1, %2 etc refer to the command line parameters which were passed to the script (%0 is the name of the script itself, %1 is the first parameter, etc). These do not need the second % character.
Similarly, if you define a temporary variable (say [tt]i[/tt]) using the [tt]for[/tt] command you can just refer to it by [tt]%i[/tt] at the command prompt or [tt]%%i[/tt] in a batch file. Don't ask me why it needs to be [tt]%%i[/tt] in a batch file, it just does.
Finally, beware of comparing a variable to a string if the variable might be empty. For example if your script contains this line
[tt]if %1==x echo Parameter was x[/tt]
then it will error if you run the script without a command line parameter (because %1 returns nothing, which == doesn't like). Instead, it's always safer to use the version with quotes:
[tt]if "%1"=="x" echo Parameter was x[/tt]
Right, I know I've tried to teach a bunch of you how to suck eggs there, but if it's of some help to at least one person I won't consider it a waste of my typing and your reading.
Hi,
your tips are very good, but what about OR condition. My code is little more complicated than my simple sample above, so with out OR i will have to use multiple sub if statements.
windows batch doesn't support "OR".
whta's complicated about it?
if %1%==x ECHO OK
if %1%==X ECHO OK
you can vb script. it's more flexible. if you can describe your project, maybe we can provide a solution.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.