Set variable to %%f [duplicate] - batch-file

This question already has answers here:
Defining and using a variable in batch file
(4 answers)
Closed 4 years ago.
I set a variable in cmd with the set command, and tried to echo it.
Here is an example:
C:\Users\Logan>set var = text
C:\Users\Logan>set var
var = text
C:\Users\Logan>echo %var%
%var%
C:\Users\Logan>
Is there a way to force the cmd to echo the variable and not the raw text?

Assigning a value/string to an environment variable
It is best to use following syntax with command extensions enabled to define or modify an environment variable:
set "var=text"
The command is set and the parameter is "variable=value".
The parameter string can be enclosed in double quotes as on all commands as long as command extensions are enabled as by default.
If the double quotes are not used around variable=value, command set interprets everything to end of line after the first equal sign including not visible spaces and horizontal tabs at end of line as string value to assign to the variable.
The name of the variable starts with first non whitespace character (after double quote if used) and ends left to first equal sign. The value assigned to the variable starts right of first equal sign and ends at end of line or last double quote.
set VAR = TEXT
The command line above creates an environment variable with name VARSpace and assigns the string SpaceTEXT to this variable.
The usage of
set var="text"
is often not correct as this results in assigning to variable var the text with the quotes included and all trailing spaces and tabs. Referencing now var on another code line with surrounding quotes often results in an error message as the variable holds itself the text already with quotes. For more details see the answer on How to set environment variables with spaces?
Example:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "var=text"
set "var = text"
set "var1=and more text"
set var2="and more text"
set var3="text with 1 trailing space"
set var
echo var3=%var3%^<- Do you see the trailing space?
echo/
set UnwantedSpaceVar=Hello
echo %UnwantedSpaceVar%! ^<- Where does the space come from?
echo/
echo There is a trailing space after Hello in this code snippet.
echo/
set "TrailingSpacesIgnored=Hi"
echo %TrailingSpacesIgnored%! ^<- The 3 trailing spaces above are ignored.
echo/
endlocal
pause
Running this small batch code results in the output:
var=text
var = text
var1=and more text
var2="and more text"
var3="text with 1 trailing space"
var3="text with 1 trailing space" <- Do you see the trailing space?
Hello ! <- Where does the space come from?
There is a trailing space after Hello in this code snippet.
Hi! <- The 3 trailing spaces above are ignored.
Enclosing variable=value in quotes can be done even if the text itself contains 1 or more double quotes.
set "Quote=""
This line defines the variable Quote with the value ". Command set interprets everything after first equal sign left to last double quote as value to assign to variable with name between the first quote and first equal sign.
Note: A string value with " inside and next & or && or || can be even on usage of set "variable=value" misinterpreted and so result in unexpected behavior as it can be seen on running a batch file with following two lines:
#echo off
set "Variable=Value with one double quote in the middle" & echo Oh, there is something wrong here!"
Value with one double quote in the middle" & echo Oh, there is something wrong here! is the string to assign to the environment variable, but assigned to the variable is just Value with one double quote in the middle and the rest of the line after " in the middle and after & interpreted as conditional operator and not literally is interpreted as additional command to execute by cmd.exe. The same problem exists with && or || after a " with 0 or more spaces/tabs between. This problem is not caused by command set. It is caused by Windows command processor which splits the line up into a command line with set and one more command line with echo with conditional execution of the echo command line.
Variable assignment with disabled command extensions
The command syntax set "variable=value" cannot be used if the command extensions are disabled with setlocal DisableExtensions in the batch file (or in Windows registry which is very uncommon and never seen by me on any Windows computer). A syntax error would be the result on execution of the batch file.
It is only possible to use set variable=value with command extensions disabled whereby the value can contain also double quotes and care must be taken on trailing spaces/tabs as they are also assigned to the environment variable.
Run in a command prompt window cmd /? and setlocal /? for more information about command extensions and which commands are affected by command extensions. Note: The output list of affected commands misses exit as described in answers on Where does GOTO :EOF return to?
Variable assignment via arithmetic expression
Using command set with option /A changes completely the parsing of second argument, i.e. the string after set /A. With option /A as first argument the second string is interpreted as arithmetic expression and being therefore processed completely different than on assigning a string value to an environment variable. Environment variables are always of type string and never of type integer.
The usage of option /A requires enabled command extensions as otherwise the command set ignores the rest of the line completely without any error message.
It is in most cases not recommended to just assign a number to an environment variable using an arithmetic expression, i.e. using set /A var=1. set "var=1" or just set var=1 (and no trailing whitespaces) are a little bit faster because environment variables are always of type string.
In an arithmetic expression whitespaces are interpreted as delimiters for variable names, numbers and operators. For that reason the command line set /A var = 1 does not define a variable with name VARSpace with the string Space1 as set var = 1 does. set /A var = 1 defines a variable with name VAR with string value 1 after converting 1 from string (batch file contains 1 as character with hexadecimal code value 31) to integer with value 1 and back to a string with the two values 0x31 and 0x00 (string terminating null).
Variable assignment via a prompt
Also using command set with option /P changes the parsing of the
string after variable name and equal sign. The string after the variable name and the equal sign is interpreted as prompt text to output and not as string to assign to the environment variable.
The environment variable gets assigned the string entered by prompted user (or redirected from a file or command/application), or in case of user does not enter anything before pressing RETURN or ENTER, keeps its current value respectively is still undefined if not defined before the prompt.
The usage of option /P requires enabled command extensions as otherwise the command set ignores the rest of the line completely without any error message.
Most used syntax for prompting a user for a string is:
set /P var="Please enter something: "
The command set removes in this case automatically the double quotes around the prompt text before printing to handle STDOUT (console window if not redirected).
But working is also:
set /P "var=Please enter something: "
Please read this answer for more details about prompt text parsing and how to output a prompt text with surrounding double quotes.

You need to remove whitespace before and after =:
set "var=text"
echo %var%
text

Related

Batch scripting - add special character to output for Codeception command

I am writing a bat file to automate the process of the below Codeception command.
php vendor/bin/codecept run tests/acceptance/SigninCest.php:^anonymousLogin$
The problem is that I cannot output the ^ character for example:
set functionNamePrefix=^^
set output=php vendor/bin/codecept run tests/acceptance/SigninCest.php:
set functionName=anonymousLogin
set functionNamePostFix=$
set command=%output%%functionNamePrefix%%functionName%%functionNamePostFix%
the $ symbol is correctly displayed but the ^ is not.
Any advice?
Thanks
Enclose the variable in quotes:
set "functionNamePrefix=^^"
Now the variable %functionNamePrefix% will contain ^.
Special characters such as the %|^ are seen as operators to cmd.
When you set functionNamePrefix=^^ and try to echo it, you effectively allow cmd to utilize the special character. Therefore, echo %functionNamePrefix% will give the more prompt, as cmd is expecting the next input line because of the ^.
When however you double quote a string, you are excluding the character in the current cmd run. It is however also recommended to double quote strings when using set to ensure you eliminate unwanted whitespace. For instance:
set var=value
Note the accidental space after value, this space will form part of the value as long as it exists, so enclose everything in double quotes to play safe and to ensure the special characters are not becoming functions in the current batch run.
set "functionNamePrefix=^^"
set "output=php vendor/bin/codecept run tests/acceptance/SigninCest.php:"
set "functionName=anonymousLogin"
set "functionNamePostFix=$"
set "command=%output%%functionNamePrefix%%functionName%%functionNamePostFix%"

What is the difference between "myvar=me" and "myvar"="me"?

I've been wondering what is the difference between "myvar=me" and "myvar"="me" in a batch file?
It might make a difference to my program which is a rock, paper, and scissors game.
The difference can be easily seen on running a batch file with following lines:
#set "myvar=me"
#set "myvar"="me"
set myvar
#pause
The first line defines an environment variable with name myvar with value me.
The second line defines an environment variable with strange name myvar" with value "me.
The third line is output by Windows command interpreter after preprocessing the command line before execution and outputs all environment variables of which name start with myvar with environment variable name, equal sign and environment variable value.
And fourth line halts batch execution until a key is pressed to see output of third line in case of batch file was executed with a double click.
So the first three lines of output are:
set myvar
myvar=me
myvar"="me
For details on how to define an environment variable right with correct assigning a value read answer on:
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
It explains with text and examples why the syntax set "variable=value" is usually the best.
That depends on context.
In case of usage inside the set command it can treat quotes as a part of a variable name and a value:
>set "a"="111"
'
>set
a"="111
...
But not in this case:
>set "a=111"
'
>set
a=111
...
Internal logic of the cmd.exe is simple is that as it eats character by character and removes quotes from the most left and right parts of a string.
Here is another context (file test.bat):
#echo off
call :TEST "1111"="2222"
call :TEST "1111","2222"
call :TEST "1111";"2222"
call :TEST "1111"-"2222"
exit /b 0
:TEST
echo -%1- -%2-
'
-"1111"- -"2222"-
-"1111"- -"2222"-
-"1111"- -"2222"-
-"1111"-"2222"- --
As you see some characters treated here as a parameter separator in a command line.
Personally I prefer to write the set "var=value" without ^-escape characters before the & and ) characters which can be part of a file path.

Why is IBM Tivoli Netcool Omnibus's Summary is not fully printed?

I need help to print an omnibus "summary" string. I have a trigger that executes a procedure:
begin
for each row critical in alerts.status where critical.AlertKey = 'DISK_USAGE_CRIT'
begin
execute send_email( critical.Node, critical.Severity, critical.AlertKey, 'NetcoolEmail', critical.Summary, 'WINITMSVR631');
end;
end
That trigger passes the values of critical node, severity, alertkey, 'NetcoolEmail', summary and host name as parameters to a procedure named send_email.
This is the procedure body:
(node char(1), severity int, situation char(1), email char(1), summary char(1), hostname (1)).
This procedure then passes the values of those parameters to variables in a batch file.
set node=%1
set situation=%3
set summary=%5
echo %node% >> C:\IBM\logtest.txt
echo %situation% >> C:\IBM\logtest.txt
echo %summary% >> C:\IBM\logtest.txt
When I echo all the variables and redirect them into a text file, the summary string is truncated while the others being printed as expected.
This is how summary variable looks if it's fully printed:
DISK_USAGE_CRIT[(%_Used>=1 AND WTLOGCLDSK.INSTCNAME AND Disk_Name="C:" ) ON Primary:WINSVR2K8:NT ON C: (%_Used=41 Disk_Name=C: )]
And yet, it is printed like this:
DISK_USAGE_CRIT[(%_Used
The rest is not being printed.
Why is the summary string not output completely?
Each percent sign % in a string which should be interpreted as literal character within a command process and not as begin/end of an environment variable reference must be doubled.
But if the summary string is passed to batch file as:
"DISK_USAGE_CRIT[(%_Used>=1 AND WTLOGCLDSK.INSTCNAME AND Disk_Name="C:" ) ON Primary:WINSVR2K8:NT ON C: (%_Used=41 Disk_Name=C: )]"
with a double quote at beginning and a double quote at end as last parameter, it is not really necessary to replace each % by %% if using in the batch file additionally delayed environment variable expansion.
The reason for the truncation is > being interpreted as command redirection operator if not found within a double quoted string and not using delayed environment variable expansion.
Therefore it is required here to use delayed expansion on echoing the values of the environment variables containing characters with special meaning for Windows command interpreter.
#echo off
setlocal EnableExtensions EnableDelayedExpansion
set "node=%~1"
set "situation=%~3"
set "summary=%~5"
echo !node!>>C:\IBM\logtest.txt
echo !situation!>>C:\IBM\logtest.txt
echo !summary!>>C:\IBM\logtest.txt
endlocal
See answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? why using set "variable=value". The first double quote is left to variable name and not right of the equal sign. This makes a big difference as the referenced answer explains in detail.
The space character left of each redirection operator >> is removed to avoid writing a trailing space on each line into the text file. The space character right of each redirection operator >> would not matter, but is here nevertheless removed, too.
For more information about delayed environment variable expansion open a command prompt window, run set /? and read all output help pages for this command very carefully.

Batch "SET" command

I keep seeing "set y=%y:~0,-2%" or some visual equivalent to it in code, but I have no idea what it's called, what it does, or how it's syntax works; I haven't been able to find an explanation, just more uses of it. Can some one explain?
"Set" sets the value of a Windows variable.
EX: set myvar=abc <= assigns the string "abc" to variable "%myvar"
"%" deferences the current value of a Windows Variable.
EX: echo %myvar% <= prints "abc"
The %y:~0,-2 syntax extracts a substring from the current value of the variable
<= extracts last 2 characters from Windows variable "%y"
Here are some useful links that might help :
Tricks with Command Line Arguments
Command line Parameters
Variable substitution
Set is used to set variables eg.: set /p A= will ask the user for input.
in cmd type set /?

Why is no string output with 'echo %var%' after using 'set var = text' command in cmd? [duplicate]

This question already has answers here:
Defining and using a variable in batch file
(4 answers)
Closed 4 years ago.
I set a variable in cmd with the set command, and tried to echo it.
Here is an example:
C:\Users\Logan>set var = text
C:\Users\Logan>set var
var = text
C:\Users\Logan>echo %var%
%var%
C:\Users\Logan>
Is there a way to force the cmd to echo the variable and not the raw text?
Assigning a value/string to an environment variable
It is best to use following syntax with command extensions enabled to define or modify an environment variable:
set "var=text"
The command is set and the parameter is "variable=value".
The parameter string can be enclosed in double quotes as on all commands as long as command extensions are enabled as by default.
If the double quotes are not used around variable=value, command set interprets everything to end of line after the first equal sign including not visible spaces and horizontal tabs at end of line as string value to assign to the variable.
The name of the variable starts with first non whitespace character (after double quote if used) and ends left to first equal sign. The value assigned to the variable starts right of first equal sign and ends at end of line or last double quote.
set VAR = TEXT
The command line above creates an environment variable with name VARSpace and assigns the string SpaceTEXT to this variable.
The usage of
set var="text"
is often not correct as this results in assigning to variable var the text with the quotes included and all trailing spaces and tabs. Referencing now var on another code line with surrounding quotes often results in an error message as the variable holds itself the text already with quotes. For more details see the answer on How to set environment variables with spaces?
Example:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "var=text"
set "var = text"
set "var1=and more text"
set var2="and more text"
set var3="text with 1 trailing space"
set var
echo var3=%var3%^<- Do you see the trailing space?
echo/
set UnwantedSpaceVar=Hello
echo %UnwantedSpaceVar%! ^<- Where does the space come from?
echo/
echo There is a trailing space after Hello in this code snippet.
echo/
set "TrailingSpacesIgnored=Hi"
echo %TrailingSpacesIgnored%! ^<- The 3 trailing spaces above are ignored.
echo/
endlocal
pause
Running this small batch code results in the output:
var=text
var = text
var1=and more text
var2="and more text"
var3="text with 1 trailing space"
var3="text with 1 trailing space" <- Do you see the trailing space?
Hello ! <- Where does the space come from?
There is a trailing space after Hello in this code snippet.
Hi! <- The 3 trailing spaces above are ignored.
Enclosing variable=value in quotes can be done even if the text itself contains 1 or more double quotes.
set "Quote=""
This line defines the variable Quote with the value ". Command set interprets everything after first equal sign left to last double quote as value to assign to variable with name between the first quote and first equal sign.
Note: A string value with " inside and next & or && or || can be even on usage of set "variable=value" misinterpreted and so result in unexpected behavior as it can be seen on running a batch file with following two lines:
#echo off
set "Variable=Value with one double quote in the middle" & echo Oh, there is something wrong here!"
Value with one double quote in the middle" & echo Oh, there is something wrong here! is the string to assign to the environment variable, but assigned to the variable is just Value with one double quote in the middle and the rest of the line after " in the middle and after & interpreted as conditional operator and not literally is interpreted as additional command to execute by cmd.exe. The same problem exists with && or || after a " with 0 or more spaces/tabs between. This problem is not caused by command set. It is caused by Windows command processor which splits the line up into a command line with set and one more command line with echo with conditional execution of the echo command line.
Variable assignment with disabled command extensions
The command syntax set "variable=value" cannot be used if the command extensions are disabled with setlocal DisableExtensions in the batch file (or in Windows registry which is very uncommon and never seen by me on any Windows computer). A syntax error would be the result on execution of the batch file.
It is only possible to use set variable=value with command extensions disabled whereby the value can contain also double quotes and care must be taken on trailing spaces/tabs as they are also assigned to the environment variable.
Run in a command prompt window cmd /? and setlocal /? for more information about command extensions and which commands are affected by command extensions. Note: The output list of affected commands misses exit as described in answers on Where does GOTO :EOF return to?
Variable assignment via arithmetic expression
Using command set with option /A changes completely the parsing of second argument, i.e. the string after set /A. With option /A as first argument the second string is interpreted as arithmetic expression and being therefore processed completely different than on assigning a string value to an environment variable. Environment variables are always of type string and never of type integer.
The usage of option /A requires enabled command extensions as otherwise the command set ignores the rest of the line completely without any error message.
It is in most cases not recommended to just assign a number to an environment variable using an arithmetic expression, i.e. using set /A var=1. set "var=1" or just set var=1 (and no trailing whitespaces) are a little bit faster because environment variables are always of type string.
In an arithmetic expression whitespaces are interpreted as delimiters for variable names, numbers and operators. For that reason the command line set /A var = 1 does not define a variable with name VARSpace with the string Space1 as set var = 1 does. set /A var = 1 defines a variable with name VAR with string value 1 after converting 1 from string (batch file contains 1 as character with hexadecimal code value 31) to integer with value 1 and back to a string with the two values 0x31 and 0x00 (string terminating null).
Variable assignment via a prompt
Also using command set with option /P changes the parsing of the
string after variable name and equal sign. The string after the variable name and the equal sign is interpreted as prompt text to output and not as string to assign to the environment variable.
The environment variable gets assigned the string entered by prompted user (or redirected from a file or command/application), or in case of user does not enter anything before pressing RETURN or ENTER, keeps its current value respectively is still undefined if not defined before the prompt.
The usage of option /P requires enabled command extensions as otherwise the command set ignores the rest of the line completely without any error message.
Most used syntax for prompting a user for a string is:
set /P var="Please enter something: "
The command set removes in this case automatically the double quotes around the prompt text before printing to handle STDOUT (console window if not redirected).
But working is also:
set /P "var=Please enter something: "
Please read this answer for more details about prompt text parsing and how to output a prompt text with surrounding double quotes.
You need to remove whitespace before and after =:
set "var=text"
echo %var%
text

Resources