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 /?
Related
I have 2 scripts:
testEnv.bat:
set TEST_VAR = "hello"
call testEnvSub.bat
testEnvSub.bat:
echo %TEST_VAR%
When I run testEnv.bat, I just get:
"ECHO is on"
So clearly the env variable I set in testEnv isn't being passed to subscript. How do I get it to pass correctly?
Question: "So clearly the env variable I set in testEnv isn't being passed to subscript."
Answer: Not at all, the variable is created, you're just not calling the correct variable name, because you created it incorrectly.
Question: "How do I get it to pass correctly?"
Answer: Unlike C+, Perl etc. Windows cmd actually uses the whitespace as part of the variable name and value. So in fact, you created a variable called %TEST_VAR % instead of %TEST_VAR% and have a value of "hello" including the leading whitespace.
So give this a go, note the double quotes starts before the variable name and closes after the value to eliminate whitespace creep.
#echo off
set "TEST_VAR=hello"
call testEnvSub.bat
Also, not that it makes much difference in execution, try and name your batch files with the .cmd extension instead of .bat it is sort off old fashioned.
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
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.
So I'm having trouble passing an argument with a period to a batch script file.
./myScript.bat 23.97
In my script, if I do
arg1 = %1
echo %arg1%
This will display 23.97 but if I do a comparison
arg1 = %1
if "%arg1%" == "23.97"
echo %arg1%
then it doesn't display at the argument at all. Fyi, i'm not trying to treat it at a float number, just a normal string. I'm no sure why it doesn't work, any help is appreciated. Thank you.
You can, in fact, have a dot (.) passed to a batch file as an argument. The section of your code that is causing you issue is the syntax that you use when setting the variable and using the if statement.
The correct syntax for setting a variable , as described by executing help set on the command line, is
Displays, sets, or removes cmd.exe environment variables.
SET [variable=[string]]
variable Specifies the environment-variable name.
string Specifies a series of characters to assign to the variable.
With this in mind, the correct way to set arg1 to the first argument passed to your batch file is
set arg1=%1
Your issue with the if statement is that you are trying to add a new line after the Boolean expression and before the next statement. The correct syntax is described by help if as
Performs conditional processing in batch programs.
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
Your if statement could be reveised to read like this:
if "%arg1%"=="29.37" echo arg1
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