How to set a variable and then use it on the same line on the command line

I want to set a variable, for example. %p% and then use it on the same line in CMD.

eg:.

 set p=notepad.exe&%p% 

This does not work. But %p% set for the next line. Therefore, if I run this line a second time, it works.

How can I use %p% on one line?

+5
source share
1 answer

When you execute a batch file, each line or block of lines (lines enclosed in parentheses) is first parsed and then executed. During the analysis, the operations of reading variables are replaced by the value inside the variable until the commands are executed. Therefore, if the value of a variable changes in a row / block, you cannot get this changed value, because the analyzer deleted the read operation with the value in the variable before the change was made.

So your code

 set p=notepad.exe&%p% 

parsed and converted to

 set p=notepad.exe& 

where the read operation to get %p% been replaced by the value in the variable (the sample assumes the variable is empty). Then this parsed line is executed.

Why is he working a second time? Since the variable was set in the previous run and, if it was not reset, when the parser performs the replacement in the second run, the variable contains the value for the replacement in the string.

To see that this is parsing before execution, you can change your line to

 set p=notepad.exe&set p 

that is, set the variable and upload the contents of the environment (variables starting with p), and you will see that the variable is set to notepad.exe . Since this line does not contain any read operation in the variable, everything works as expected.

How to solve your problem? There are several options

Deferred extension

If slow expansion is enabled, the syntax for reading variables can be changed, if necessary, from %var% to !var! , indicating to the parser that the substitution in the read operation should be delayed until the execution of the command

 setlocal enabledelayedexpansion set p=notepad.exe&!p! 

The same behavior can be activated if the shell is invoked with /v:on

 cmd /v:on /c "set p=notepad.exe&!p!" 

Force second command syntax

This uses the call command to force the second syntax in a string

 set p=notepad.exe&call %%p%% 

The first parser, by default, replaces the literal %%p%% literal %p% ( %% is an escaped percent icon) without performing a variable change, and when the call command is executed, the string is parsed again, so the %p% literal is interpreted as reading a variable and replaced by the value in the variable

What to use? It depends. A delayed extension decision has a better execution time at which a call solution (the call command does a lot more work), but with the extension delay turned on, exclamation points ( ! ) In the data become a problem that needs to be properly handled.

+10
source

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


All Articles