% or ! and variables? - any rules with delayed expansion

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Jer
Posts: 177
Joined: 23 Nov 2014 17:13
Location: California USA

% or ! and variables? - any rules with delayed expansion

#1 Post by Jer » 24 Jan 2015 19:42

I am working on a large batch file program that includes For loops, and I am using setlocal enabledelayedexpansion
at the batch code level and in functions. Can anyone explain what controls a variable's assignment when you are using
%var% or !var! and testing for the current value. I've found that %var% can have a previous value while !var! has the current value.
I am assigning a specific variable at more than one place in the code. An example: at the start of the batch file, if a file
exists, I read a file name from its first line and assign that name, including the path, to the variable, and the 1-panel file will be typed out.
This panel is the last panel viewed when the program was last exited in the normal way.
During the program's use, prompted input determines what the next panel will be, and that file and path gets assigned to the variable before
the panel is typed out.

Rather than just doing what works, I would like to know if there is documentation or an explanation of coding variables and the correct
syntax when using delayed expansion
Thanks.

Squashman
Expert
Posts: 4488
Joined: 23 Dec 2011 13:59

Re: % or ! and variables? - any rules with delayed expansion

#2 Post by Squashman » 24 Jan 2015 19:46

There is a nice long thread about how cmd.exe works but here is the basic premise for delayed expansion.

Basically when you are inside a (CODE BLOCK), meaning you have a bunch of code inside parenthesis, and you are manipulating the values of your variables inside the CODE block, then you need to use !VAR! for your variable references.

But if you could provide specific code examples of what you are trying to do, we could probably give you a better understanding of what is happening with your code.

You can start reading this thread on SO.
http://stackoverflow.com/a/4095133/1417694

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: % or ! and variables? - any rules with delayed expansion

#3 Post by foxidrive » 25 Jan 2015 05:35

Just to add a comment that may apply to the OP's code:

If you use delayed expansion and always use !variable! then the variable will always have the latest data.

Using endlocal changes this, as it removes all variables that are changed after the setlocal ...
and when using enabledelayedexpansion then the ! becomes a poison character.

Post Reply