Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable assignment in batch

This question seems to be (very) stupid be I can't deal with it :(

When I tried this batch code:

if "%1" == "-i" (
set is = %2
echo. %is%
shift
)

called with 2 (or more) arguments, it does NOT work. It actually prints a blank. The "shift" command is not done either. When I watch the executed code (without the @echo off at the beginning), I can see that the "set" command is completed.

What's wrong with it?

Example of calling:

c:\script.bat -i test -d bla
like image 309
el_grom Avatar asked Feb 03 '26 06:02

el_grom


1 Answers

You have two issues. By default group of statements in parens will have variable expansion done all at once, that is before your set command. Also the semantics for set is wrong, you don't want spaces around the =.

Add this to the top of your file:

setlocal ENABLEDELAYEDEXPANSION

and remove the spaces around = in set:

set is=%2

Finally used delayed expansion:

echo. !is!

A possible third issue is you may need two SHIFTs, one for -i, one for it's is argument.

Update

Thanks to @dbenham for pointing out that it wasn't a syntax error with set, it's just surprising behavior that deserves a little explanation. If you execute these commands:

set a=one
echo "%a%"

The result is:

"one"

That makes sense, but try:

set b = two
echo "%b%"

And you get:

"%b%"

What? This is what you would expect when environment var b is unset. But we just set it. Or did we:

echo "%b %"

Displays:

" two"

For the Windows set command, unlike any other language or environment I'm aware of, the spaces are significant. The spaces before the = become part of the environment var name, spaces after become part of the value. This uncommon behavior is a common source of errors when writing Windows batch programs.

like image 170
jimhark Avatar answered Feb 07 '26 07:02

jimhark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!