Run two commands on the same cmd line, one command - SET command

[target]

This simple command sequence runs in the Windows CMD shell:

dir & echo hello 

will list files and directories and an echo line.

However, the following sequence of commands does not start as expected (at least by me):

 C:\Users\Administrator>set name=value & echo %name% %name% C:\Users\Administrator>echo %name% value C:\Users\Administrator> 

As we see, the first echo cannot receive the medium. Could you comment? Any comment would be appreciated!

PS: OS: Windows 7 X64 Home Pre

+6
source share
2 answers

Your result is due to the fact that% name% is expanded during the parsing phase, and the entire line is parsed immediately to the set value.

You can get the current value on the same line as the set command in one of two ways.

1) use CALL to call ECHO% NAME% for analysis the 2nd time:

 set name=value&call echo %^name% 

I put ^ between percentages only if the name was already defined before the line was executed. Without a carriage, you get the old value.

Note: the source line had a space before & , this space would be included in the value of the variable. You can prevent extra space by using quotation marks: set "name=value" &...

2) use a delayed extension to get the value at runtime, not during parsing. Most environments do not enable slow extension by default. You can enable slow extension on the command line with the appropriate CMD.EXE option.

 cmd /v:on set "name=value" & echo !name! 

A delayed extension can certainly be used on the command line, but is more commonly used in a batch file. SETLOCAL is used to enable slow extension in a batch file (it does not work from the command line)

 setlocal enableDelayedExpansion set "name=value" & echo !name! 
+10
source

You can also use cmd /V /C (c /V to enable slow expansion).
It is advisable to set the environment variable for only one command in Windows cmd.exe :

 cmd /V /C "set "name=value" && echo !name!" value 

Note the use of double quotes in set "name=value" to avoid extra space after value .
For example, without double quotes:

 cmd /V /C "set name=value && echo '!name!'" 'value ' 

You will need to think to remove the space between value and && :

 cmd /V /C "set name=value&& echo '!name!'" 'value' 

But the use of double quotes makes the assignment more explicit.

+2
source

Source: https://habr.com/ru/post/911746/


All Articles