开发者

Is It possible to set environment variable and echo it in a single line batch script?

set A=2 && echo %A%

This does not echo A as 2 in windows. Is there any way to 开发者_Python百科do it?

A=2 ; echo $A

works in bash. I want a similar behavior on windows


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" set results for 2nd solution, thanks Johannes Rössel


Note the ! surrounding A instead of %.

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


Adding to @Anders answers, I tweaked his solution to something that gives you a bit more flexibility:

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

Output:

bar

This enables you to do string replacement too:

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

Output:

bor

Edit: added some carets to fix @jeb's remark.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜