3

On Windows command prompt:

D:\> echo %undef%
%undef%

D:\> type undef.bat
echo %undef%
D:\> undef

D:\> echo
ECHO is on.

My question is why on command line undefined environment variables like %undef% are expanded to %undef% but in BAT files are expanded to empty string?

csharpfolk
  • 4,124
  • 25
  • 31
  • 2
    It's just one of several behaviors that is different on the command line than in a batch file, like having to double your `%%` signs in a `for` statement. – Ryan Bemrose Sep 26 '16 at 16:40
  • @RyanBemrose may it be, but this looks like it was deliberately designed this way, why shell programmers should implement two different set of rules it only makes shell code more compilcated – csharpfolk Sep 26 '16 at 16:45
  • 1
    Very little about batch was deliberately *designed*. It evolved from MS-DOS more than 30 years ago, and has only had features added that can keep compatibility with scripts older than most programmers. If you want a language that has good *design*, you need something invented more recently. – Ryan Bemrose Sep 26 '16 at 16:49
  • @RyanBemrose you have a point – csharpfolk Sep 26 '16 at 17:02
  • 2
    [Here](http://stackoverflow.com/q/4094699/2861476) you can read *how* Probably no one out of Microsoft could properly answer *why*. My bet: the output in command line context makes it *"easier"* to see the command makes reference to a undefined variable. But I don't see a clear reason not to do the same inside batch files. – MC ND Sep 26 '16 at 17:28
  • 3
    @MCND, actually I'd prefer `cmd` to behave like batch files, not the other way round, because returning empty lines is quite often needed; anyway, I stopped asking for reasons years ago... ;-) – aschipfl Sep 26 '16 at 18:32

1 Answers1

0

for /f "tokens=* delims=" %S IN ('help^|find /i "for "') do echo %S in cmd.exe

vs

for /f "tokens=* delims=" %%S IN ('help^|find /i "for "') do echo %%S in batfile

for understand:

@set 1=
@echo %1
@echo %1%
@set 1=interactive only
@echo %1%

returns in cmd.exe:

%1
%1%
interactive only

but in batfile when that running with some options (for example: "first" "second")

"first"
"first"
"first"

it's doing for arguments escape (for get > 9 argument use shift command)