The Windows .Bat Variable Quirk That Cost Us an Hour

Posted on:

Variables in the Windows CLI have an interesting property that makes how you set them important

We had a bit of fun at work today, trying to figure out why on earth 3GB of seemingly junk data had been copied into a folder my colleague was working in.

Jack had been trying to copy a single file called %file% from %TEMP% to a folder we’ll call %destination%. With the rest of the unnecessary code stripped away, this is essentially what he had:

Seems… pretty normal right? So where was all this junk coming from? Closer inspection of the files didn’t exactly give any helpful clues; it consisted of odd .html files, some small gifs and even the Java 7 installation file.

Clearly something was up with our copying, so we added an echo before line 4, and got this wonderful response out:

copy C:\Users\Jack\AppData\Local\Temp /some/folder/

Now, excuse me if I’m wrong but, but we seem to be missing one "importantfile.xml".

So we’ve figured out why we’re getting junk and the whole script is taking suspiciously long to run - there’s no file being specified, so the whole folder gets copied instead! What joy. But now we have to ask ourselves, why is there no file?

Take a good look back at line 2. Notice how it differs from line 1? Yep. There’s a space after the word “file”.

We didn’t set the variable %file%, we set the variable %file % instead. Note the space. Goddammit Windows.

Where the rest of the hour went

Luckily we managed to solve this one pretty quickly. The real fun arrived with a Python script the batch file was calling. It was throwing all sorts of fun exceptions and errors, but none of any substance.

I’ll save you a mildly frustrating story that involves going round in circles: The real culprit was, again, a variable passed in from the .bat file with an extra space ruining it.

What we learnt

Screw batch files.

Also, watch out for spaces when setting variables in batch files.

Do you know of any other languages with tiny quirks like this that can screw you over if you’re looking out for them? (I’m looking at you, PowerShell.)