Is it possible to set an environment variable and echo in a separate script line?

set A=2 && echo %A%

      

This does not reflect A as 2 in windows. Is there a way to do this?

A=2 ; echo $A

      

works in bash. I need similar behavior on windows

+2


a source to share


3 answers


I'm sure there are many ways to do this, here are two of them:

  • setlocal ENABLEDELAYEDEXPANSION&set "foo=bar baz"&echo.!foo!&endlocal

  • set "foo=bar baz"&for /F "tokens=1,* delims==" %%A in ('set foo') do if "%%~A"=="foo" echo.%%B



Edit: Added check to "filter" the set results for the second solution, thanks to Johannes Rössel

+1


a source


Pay attention to the !

surroundings A

instead %

.



@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET A=2 & ECHO !A!
ENDLOCAL

      

0


a source


Adding to @Anders' answers , I changed his solution to something that gives you a little more flexibility:

set foo=bar&for /f %a in ('echo ^%foo^%') do @echo %a

      

Output:

bar

      

This also allows for string replacement:

set foo=bar&for /f %a in ('echo ^%foo^:a^=o^%') do @echo %a

      

Output:

bor

      

Edit: added some quotes to correct @ jeb's note.

0


a source







All Articles