Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOS batch: SET variable and ECHO it within (...) block

Tags:

batch-file

cmd

I had a problem with set not working in a batch file; it took a while to distil the problem; at first I thought it was to do with subroutine calls...

The script

@echo off
setlocal
set a=aaa
echo a = "%a%"
(
set b=bbb
echo b = "%b%"
)

produces the output

a = "aaa"
b = ""

whereas I'd expect

a = "aaa"
b = "bbb"

Why is this please? Is it a bug in DOS? Perhaps there's something about the (...) command grouping syntax that I'm unaware of.

Thanks.

like image 202
Rhubbarb Avatar asked Nov 06 '09 12:11

Rhubbarb


2 Answers

User delayed expansion and ! instead of %

@echo off
setlocal enableextensions enabledelayedexpansion
set a=aaa
echo a = "%a%"
(
set b=bbb
echo b = "!b!"
)
like image 76
Andy Morris Avatar answered Oct 10 '22 02:10

Andy Morris


What's happening is that the batch interpreter as treating everything in between the brackets a single line. This means it's doing variable replacement on everything betweeen the brackets before any of the commands are run.

So:

(
set b=bbb
echo b = "%b%"
)

Becomes:

(
set b=bbb
echo b = ""
)

The variable b is being set but obviously isn't set before you run the SET command.

like image 45
Dave Webb Avatar answered Oct 10 '22 02:10

Dave Webb