panny
panny

Reputation: 2212

cmd environment variable behaviour unclear

I'm kind of struggling with cmd.exe so let me put this in code:

           :: Set an environment variable var to `pwd` 
           :: (forget about the backslashes)
C:\somedir>set var=C:\\\somedir\\\ & call echo %var%
C:\\\somedir\\\    

           :: great! works.
           :: Is the environment variable really there?
C:\somedir>set v
var=C:\\\somedir\\\    

           :: yes. ok.
           :: Traverse directory recursively, find class files ending with T, 
           :: delete `pwd` from filenames:
C:\somedir>dir /s /b *T.class | grep T\. | sed 's/%var%//g'
C:\somedir\domain\test\ClassT.class  

           :: uh oh no! Didn't work.
           :: Wait a minute. Is the environment variable really there?
C:\somedir>set v
var=C:\\\somedir\\\                 

           :: hmm...yes, indeed?
           :: ok. Take a breath. Start over. Empty/Delete var.
C:\somedir>set var=

           :: Manually fill var
C:\somedir>set var=C:\\\somedir\\\

           :: Try again...
C:\somedir>dir /s /b *T.class | grep T\. | sed 's/%var%//g'
domain\test\ClassT.class         

           ::YES! uh...oh...no...w**hy does it not work above?

The question is, why can't I use var in the pipeline although it is available in the environment and what is changed when I set var "manually" as opposed to set var=C:\\\somedir\\\ & call echo %var% which is, for the first part perfectly legal exactly manual as later in the listing.

Upvotes: 1

Views: 105

Answers (1)

BartekB
BartekB

Reputation: 8660

In this case you are actually setting var to c:\\\somedir\\\<whitespace> Yes, cmd is not really smart with setting variables.

In latter example you probably hit enter as soon as you get to "\". To be sure - use ():

(SET VAR=c:\\\windows\\\) & echo %VAR%
:: Test for trailing space...
echo [%VAR%]

Upvotes: 2

Related Questions