Kamal
Kamal

Reputation: 3158

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 do it?

A=2 ; echo $A

works in bash. I want a similar behavior on windows

Upvotes: 2

Views: 747

Answers (3)

Grimace of Despair
Grimace of Despair

Reputation: 3506

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.

Upvotes: 0

Anders
Anders

Reputation: 101606

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

Upvotes: 1

aphoria
aphoria

Reputation: 20179

Note the ! surrounding A instead of %.

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

Upvotes: 0

Related Questions