Search code examples
batch-filedos

Safe way to concatenate DOS variables to avoid unseen tab characters causing a double execution of a DEL command?


I have a batch file: C:\zzzztemp\zzzBUG_TEST.cmd

set backup_folder=.\BUG_TEST
echo %backup_folder%\*.*
del %backup_folder%\*.*
pause

...whose output is:

C:\zzzztemp>set backup_folder=.\BUG_TEST

C:\zzzztemp>echo .\BUG_TEST\*.*
.\BUG_TEST\*.*

C:\zzzztemp>del .\BUG_TEST\*.*
C:\zzzztemp\BUG_TEST\*.*, Are you sure (Y/N)? y

C:\zzzztemp>pause
Press any key to continue . . .

So far so good, just as expected.

But, if I accidentally have a tab at the end of specifying the folder variable

set backup_folder=.\BUG_TEST{accidentally had a tab here}

Results in:

C:\zzzztemp>set backup_folder=.\BUG_TEST

C:\zzzztemp>echo .\BUG_TEST     \*.*
.\BUG_TEST      \*.*

C:\zzzztemp>del .\BUG_TEST      \*.*
C:\zzzztemp\BUG_TEST\*, Are you sure (Y/N)? y
C:\*.*, Are you sure (Y/N)?

As you can see from the echo output, this is being interpreted as two arguments to the DEL command, and as a result the DEL operation is being performed twice, on two folders, one of which is c:\*.*

If one was to run this delete with the /Q (quiet, not requiring prompt to confirm delete), he could wipe out all the files in the root of c: !!!

So, I guess my question comes down to...

Is there a safe way to write:

del %backup_folder%\*.*

...Such that I would get a runtime error rather than an unintentional execution of delete with two arguments in the event that an unseen tab gets appended onto the variable assignment?


Solution

  • set "backup_folder=.\BUG_TEST" extra chars after last quote are ignored
    

    Any characters after the last quote in the above assignment are ignored. No more accidental trailing tabs or spaces in your assignments :-)