Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows command line: why environment variable is not available after &

Have a look at the following commands: why is the value of a not available immediately after the &?

C:\>set a=

C:\>set a=3&echo %a%
%a%

C:\>echo %a%
3

C:\>set a=3&echo %a%
3

But when I do

C:\>set a=

C:\>set a=3&set

a=3 is included in the listed variables!

I need this for a trick I learned here, to get the exit code of a command even output is piped: Windows command interpreter: how to obtain exit code of first piped command but I have to use it in a make script, that's why everything must be in one line! This is what I am trying to do:

target:
    ($(command) & call echo %%^^errorlevel%% ^>$(exitcodefile)) 2>&1 | tee $(logfile) & set /p errorlevel_make=<$(exitcodefile) & exit /B %errorlevel_make%

But errorlevel_make is always empty (the file with the exit code exists and contains the correct exit code).

Is this a bug in cmd? Any ideas what I can do?

like image 507
user2452157 Avatar asked Oct 23 '13 14:10

user2452157


People also ask

How do I get my Windows environment variables back?

Navigate to C:\Windows\system32\ and find cmd.exe. Right-click on cmd.exe and click Open. This will bring up a command prompt with the environment variables of the software (chrome in this instance) and you can echo %path% to get your old env variables!

How do I set environment variables permanently?

To make permanent changes to the environment variables for all new accounts, go to your /etc/skel files, such as . bashrc , and change the ones that are already there or enter the new ones. When you create new users, these /etc/skel files will be copied to the new user's home directory.


1 Answers

The reason for the observed behaviour is how the command line is processed.

In first case set a=3&echo %a%, when the line is interpreted BEFORE EXECUTING IT, all variables are replaced with their values. a has no value until line executes, so it can not be substituted in echo

In second case, set a=3&set, there is no variable substitution before execution. So, when set is executed, a has the value asigned.

like image 105
MC ND Avatar answered Nov 15 '22 04:11

MC ND