Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Setting variables in a local scope in .cmd files

Status
Not open for further replies.

Salem

Programmer
Apr 29, 2003
2,455
GB
Hello,

I have a test script which reads like this
Code:
@echo on

set Z_FOO=yes
echo yes=%Z_FOO%

if "%Z_FOO%" equ "yes" (
  rem setlocal
  set Z_FOO=no
  set
  echo yes=%Z_FOO%
  rem endlocal
)
echo all done

When I run this with [tt]cmd /c test.cmd[/tt] say, I get these results.
Code:
> set Z_FOO=yes

> echo yes=yes
yes=yes

> if "yes" EQU "yes" (
rem setlocal
 set Z_FOO=no
 set
 echo yes=yes
 rem endlocal
)
ComSpec=C:\WINDOWS\system32\cmd.exe
Path=C:\WINDOWS\system32;
PATHEXT=.COM;.EXE;.BAT;.CMD
PROMPT=$G$S
Z_FOO=no
yes=yes

> echo all done
all done
Now the assignment seems to have worked, because the set command is indeed printing the new value (no), but the echo command is still printing the old value (ie, yes).

I was expecting a "yes=no" to be printed.

Uncommenting the setlocal/endlocal doesn't help either.

Looking at the output, it seems like everything between the () is being copied "as is" to a temporary file and then executed, thereby bypassing any subsequent assignments and use of variables.

Is there any way to get the new value of the variable to be used in the () part of the script?
I'd rather not have to reverse the test and use lots of goto's - I have many similar tests in a larger script I'm trying to develop.

Thanks for any info.

--
 
After a real quick glance at this, I suspect that only a single command is allowed within parens rather than a series of statements. I don't see a way around using GOTOs if code blocks aren't supported.
 
Try using an ELSE statement. Might be easier.

@echo on

set Z_FOO=yes
echo yes=%Z_FOO%

if "%Z_FOO%" equ "yes" (set Z_FOO=no) ELSE (set Z_FOO=yes)
set
echo yes=%Z_FOO%
echo all done
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top