What is "delayed environment variable expansion" - windows

Is there someone to explain exactly what is delayed environment variable expansion in simple terms or point to a post that can understand. Here is my questions
What can't I achieve without this
In which practical situations uses this
Any alternative

%Var% is expanded when a line is read. As lines can have multiple commands, !var! is expanded when used. In MS-DOS !var! (accessed in script by %!var!%) is a legal variable name so you have to turn on a special mode to access. This is so MS-DOS batch files can run in CMD without editing.

Related

Can history expansion (exclamation mark) be disabled on Windows shell?

When I run a command like this:
someprogram.exe --param="Value!"
the Windows shell will treat the exclamation mark in my value as a special character. Is there a way to suppress that or is escaping the only way around this? (Exclamation mark is escaped by ^^! if I'm not mistaken.)
EDIT: Weird thing that cmd.exe does not do the expansion but cmder does. I thought they are just two different GUIs to the same underlying shell? Maybe there's a switch for the expansion behavior? I tried SETLOCAL DisableDelayedExpansion but with no effect.

How are environment variables used in Jenkins with Windows Batch Command?

I'm trying to use Jenkins (Global) environment variables in my xcopy script.
${WORKSPACE} doesn't work
"${WORKSPACE}" doesn't work
'${WORKSPACE}' doesn't work
I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.
If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE
echo %WORKSPACE%
If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &, &&, or || are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.
setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
set WORKSPACE=AFTER
echo Normal Expansion = %WORKSPACE%
echo Delayed Expansion = !WORKSPACE!
)
The output of the above is
Normal Expansion = BEFORE
Delayed Expansion = AFTER
Use HELP SET or SET /? from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.
In windows you should use %WORKSPACE%.
I should this On Windows, environment variable expansion is %BUILD_NUMBER%

Manipulating variables in windows

I know there are a few things you can do directly with a variable, such as cut off ends of the variables via %var:~0,4%, or even do character replacement via %var:/=-%. What are these features called? And does anyone have a link to documentation for them?
It's the old dos string manipulation. See http://www.dostips.com/DtTipsStringManipulation.php
I would say "Environment variable substitution" as described in SET /? (although this omits to mention parameter substitution commands like %~nxN for extracting a file name from a path passed as the Nth command line argument).

Dealing with quotes in Windows batch scripts

In a Windows batch file, when you do the following:
set myvar="c:\my music & videos"
the variable myvar is stored with the quotes included. Honestly I find that very stupid. The quotes are just to tell where the string begins and ends, not to be stored as part of the value itself.
How can I prevent this from happening?
Thanks.
set "myvar=c:\my music & videos"
Notice the quotes start before myvar. It's actually that simple.
Side note: myvar can't be echoed afterwards unless it's wrapped in quotes because & will be read as a command separator, but it'll still work as a path.
http://ss64.com/nt/set.html under "Variable names can include Spaces"
This is the correct way to do it:
set "myvar=c:\my music & videos"
The quotes will not be included in the variable value.
It depends on how you want to use the variable. If you just want to use the value of the variable without the quotes you can use either delayed expansion and string substitution, or the for command:
#echo OFF
SETLOCAL enabledelayedexpansion
set myvar="C:\my music & videos"
As andynormancx states, the quotes are needed since the string contains the &. Or you can escape it with the ^, but I think the quotes are a little cleaner.
If you use delayed expansion with string substitution, you get the value of the variable without the quotes:
#echo !myvar:"=!
>>> C:\my music & videos
You can also use the for command:
for /f "tokens=* delims=" %%P in (%myvar%) do (
#echo %%P
)
>>> C:\my music & videos
However, if you want to use the variable in a command, you must use the quoted value or enclose the value of the variable in quotes:
Using string substitution and delayed expansion to use value of the variable without quotes, but use the variable in a command:
#echo OFF
SETLOCAL enabledelayedexpansion
set myvar="C:\my music & videos"
md %myvar%
#echo !myvar:"=! created.
Using the for command to use the value of the variable without quotes, but you'll have to surround the variable with quotes when using it in commands:
#echo OFF
set myvar="C:\my music & videos"
for /f "tokens=* delims=" %%P in (%myvar%) do (
md "%%P"
#echo %%P created.
)
Long story short, there's really no clean way to use a path or filename that contains embedded spaces and/or &s in a batch file.
Use jscript.
Many moons ago (i.e. about 8 years give or take) I was working on a large C++/VB6 project, and I had various bits of Batch Script to do parts of the build.
Then someone pointed me at the Joel Test, I was particularly enamoured of point 2, and set about bringing all my little build scripts into one single build script . . .
and it nearly broke my heart, getting all those little scripts working together, on different machines, with slightly different setups, ye Gods it was dreadful - particularly setting variables and parameter passing. It was really brittle, the slightest thing would break it and require 30 minutes of tweaking to get going again.
Eventually - I can be stubborn me - I chucked the whole lot in and in about a day re-wrote it all in JavaScript, running it from the command prompt with CScript.
I haven't looked back. Although these days it's MSBuild and Cruise Control, if I need to do something even slightly involved with a batch script, I use jscript.
The Windows command interpreter allows you to use the quotes around the entire set command (valid in every version of windows NT from NT 4.0 to Windows 2012 R2)
Your script should just be written as follows:
#echo OFF
set "myvar=C:\my music & videos"
Then you may put quotes around the variables as needed.
Working with the CMD prompt can seem esoteric at times, but the command interpreter actually behaves pretty solidly in obeying it's internal logic, you just need to re-think things.
In fact, the set command does not require you to use quotes at all, but both the way you are doing your variable assignment and the way the ,method of using no quotes can cause you to have extra spaces around your variable which are hard to notice when debugging your script.
e.g. Both of the below are technically Valid, but you can have trailing spaces, so it's not a good practice:
set myvar=some text
set myvar="some text"
e.g. Both of the below are good methods for setting variables in Windows Command interpreter, however the double quote method is superior:
set "myvar=Some text"
(set myvar=Some value)
Both of these leave nothing to interpretation the variable will have exactly the data you are looking for.
strong text However, for your purposes, only the quoted method will work validly because you are using a reserved character
Thus, you would use:
set "myvar=c:\my music & videos"
However, even though the variable IS correctly set to this string, when you ECHO the sting the command interpreter will interpret the ampersand as the keyword to indicate another statement follows.
SO if you want to echo the string from the variable the CMD interpreter still needs to be told it's a text string, or if you do not want the quotes to show you have to do one of the following:
echo the variable WITH Quotes:
Echo."%myvar%"
echo the variable WITHOUT Quotes:
Echo.%myvar:&=^&%
<nul SET /P="%myvar%"
In the above two scenarios you can echo the string with no quotes just fine. Example output below:
C:\Admin> Echo.%myvar:&=^&%
C:\my music & videos
C:\Admin> <nul SET /P="%myvar%"
C:\my music & videos
C:\Admin>
Try using the escape character '^', e.g.
set myvar=c:\my music ^& videos
You'll have you be careful when you expand myvar because the shell might not treat the & as a literal. If the above doesn't work, try inserting a caret into the string too:
set myvar=c:\my music ^^^& videos
Two solutions:
Don't use spaces or other characters that are special to the command interpreter in path names (directory or file names). If you use only letters, numbers, underscores, and hyphens (and a period before the extension to identify the file type), your scripting life will become immeasurably simpler.
I have written and otherwise collected a plethora of tools over the years, including a DOS utility that will rename files. (It began as something that just removed spaces from filenames, but morphed into something that will replace characters or strings within the filenames, even recursively.) If anyone's interested, I will get my long-neglected web site up and running and post this and others.
That said, variables aren't just for holding pathnames, so...
As others have already pointed out, SET "myvar=c:\my music & videos" is the correct workaround for such a variable value. (Yes, I said workaround. I agree that your initial inclination to just quote the value ("my music & videos") is far more intuitive, but it is what it is, as they say.

Unexpected variable substitution behavior in Windows .bat file

The code is,
set VAR=before
if "%VAR%" == "before" (
set VAR=after;
echo %VAR%
)
What will the preceding Windows .bat file code segment display? Why? (i.e. why doesn't it behave as you might first think)?
Obviously, you'd think the output would be "after", given that we reset the env variable inside the loop.
But the output will actually be "before". The reason is that variable substitution is done in .bat files by the interpreter when a command is read, rather than when it's executed. So, for the compound statement, the variables in the body are evaluated when the if statement is first encountered.
You can make this work by using delayed environment variable expansion (need to enable it). If it's enabled, you can then do:
set VAR=before
if "%VAR%" == "before" (
set VAR=after;
echo !VAR!
)
You can enable delayed environment variable expansion using the /v option when starting cmd.exe.
[Backstory--many of us still use legacy .bat files to drive things like make procedures, etc. Obviously there are better scripting tools, but not always an option to use them. I ran into this issue a while back and recently found two other people who had pulled their hair out over the same thing. So it's useful to understand how the interpreter does variable substitution].
The substitution for %VAR% occurs before the execution of the command. Even though there are several commands spread over several lines, the grouping of them in parens (...) causes the cmd.exe parser to read the whole thing in as a single command. So what gets executed looks like the following to the interpreter.
set VAR=before
if "before" == "before" (
set VAR=after;
echo before
)
This is one of the many things that make batch file processing rather painful hen trying to do anything more than simple stuff.

Resources