Multi-Line IF Statements in Batch File
Most folks don't realize it, but you can actually place multiple statements into if-else clauses. In fact, most people don't even realize that the batch file allows you to have an else clause. The following code demonstrates how you can have multi-line IF statements, so that you don't have to do a lot of goto's.
if exist %sourceDir% (
The '(' and ')' must be on the same line as the if and else statements as shown above. Even though they are not the open and close bracket, you can think of them as such. With multi-line if-else statements, you batch file can become far more structured than ever.
I hit a snag today. The set variable function does not work inside a multi-statement if-else scope. For example, the following code does not work:
if "%tempDir%" == "" (
The batch processor was never able to use the %output% that was set within that scope.
The work around for this problem is to call a sub-routine in the if statement. The following is an example:
if "%tempDir%" == "" (
Have you tried to at the beginning of your code set
and before exiting from the script code
Just tried it, johan. That didn't work. :-( The following is the prototype code:
Instead of printing "*** just some text", the output was "ECHO is off." . . . meaning %output% wasn't assigned a value.
It unsures that the echo output command doesn't get confused with the echo on/off command. Seems like it's reading your output variable and defaulting ECHO to off because it's not a valid parameter (on or off). You've probably got over this problem by now, but this may help someone else.
Replacing the % with ! will solve your problem with setting a variable in a loop.
Thanks, TheBlackOne! That worked. Delayed expansion has to be enabled for this trick to work. The following is an example batch program that demonstrates this trick.
I want to add to the previous comment that you can use the new variable within the IF clause outside the IF clause scope. The following example expands on the previous one and shows how it can be used outside the scope.
You are great!
Found another interesting side-effect. If "!output!" is assigned within the if-clause, then "%output%" will be assigned after exiting the if-clause scope. Use following example:
The output is as follows:
ECHO is off.
Notice that "%output%" cannot be reference in the if-clause scope, but it can be referenced in the global scope.
Thanks for teaching me the call subroutine command. If statements are quite fickle and cmd batch scripts, sometime collapsing the script for no reason. Simplifying the if statement by making it call a subrountine really helped.
Did your message disappear? Read the Forums FAQ.
TrackBack only accepted from WebSite-X Suite web sites. Do not submit TrackBacks from other sites.
Title: SetVariableToOutput.bat (GPL)
Spam Control | * indicates required field
Messages, files, and images copyright by respective owners.
36 Users Online
Copyright © 1996 - 2020. All Rights Reserved.