Lewis Kelsey
Lewis Kelsey

Reputation: 4687

Why is a single % in a for loop not interpreted as an environment variable at the command line but it is in a batch file?

On this question, this remains unanswered:

Is there an explanation for why I can get away with using just one percent sign in a FOR loop, when executed directly from a command prompt, and not from a batch file? I know about the DOS heritage, but we can use variables from a command line now.

You can use environment variables on the command line so why is something like FOR /L %A in (1,1,5) Do Echo %A not interpreted as the %A in (1,1,5) Do Echo % environment variable on the command line as well?

Upvotes: 2

Views: 187

Answers (1)

dbenham
dbenham

Reputation: 130879

I don't know the reason why the command line parsing is so different than the batch mode parsing. Probably something to do with backward compatibility with old DOS behavior.

But the command line does attempt to treat %A in (1,1,5) Do Echo % as a variable!

D:\test>FOR /L %A in (1,1,5) Do Echo %A

D:\test>Echo 1
1

D:\test>Echo 2
2

D:\test>Echo 3
3

D:\test>Echo 4
4

D:\test>Echo 5
5

D:\test>set "A in (1,1,5) Do Echo =XXXX"

D:\test>FOR /L %A in (1,1,5) Do Echo %A
XXXXA was unexpected at this time.

In the first instance the odd variable is not defined, so the FOR command succeeds. The second time the odd variable is defined, and the expansion results in an invalid command.

Command line mode does not expand an undefined variable to nothing, but rather preserves the initial % and then looks for other variables to expand afterward.

For example, if X is undefined, and Y=1, then %X%Y% will expand to %X1 on the command line. But in a batch file it will expand to Y.

The outcomes are fully predicted by the rules posted at https://stackoverflow.com/a/7970912/1012053, but it can be hard to follow.

Upvotes: 1

Related Questions