batch file: pass parameter with white spaces to function

Matthias Pospiech picture Matthias Pospiech · Jul 13, 2011 · Viewed 14.2k times · Source

I am using a batch file for backups. I pass the options to a function which calls the packaging executable. This works unless the parameters contain whitespaces. This is the relevant code:

SET TARGET="%SAVEDIR%\XP.User.Documents.rar"
SET FILES="%DIRUSER%\Eigene Dateien\*"      
SET EXLUCDE="%DIRUSER%\Documents\CDs" 
call:funcBackup %TARGET% %FILES% %EXLUCDE%

:funcBackup
    SET TARGET=%~1
    SET FILES=%~2
    SET EXCLUDE=%~3     
    echo."%PACKER% a -r -x"%EXCLUDE%" "%TARGET%" "%FILES%""
    ::call %PACKER% a -r -x"%EXCLUDE%" "%TARGET%" "%FILES%"
goto:eof

On XP(german version) %DIRUSER% expands to "Dokumente und Einstellungen"

In that case TARGET is correct, but FILES == "Dokumente" and EXCLUDE == "und", which means that the script fails because of the whitespaces in %DIRUSER%.

How can I fix this?

Answer

jeb picture jeb · Jul 14, 2011

The problem seems to be your style of assigning the variables.
I suppose you set the DIRUSER variable like the other ones

set DIRUSER="Dokumente und Einstellungen"

But the content of DIRUSER is then "Dokumente und Einstellungen", so the quotes are a part of the content.

But then SET FILES="%DIRUSER%\Eigene Dateien\*" expands to SET FILES=""Dokumente und Einstellungen"\Eigene Dateien\*".

You could use the extended style of set.
set "var=content" This sets the content of var to content without any quotes and also all appended spaces behind the last quote are ignored.

So your code would be

set "SAVEDIR=D:\backup"
set "diruser=Dokumente und Einstellungen"
SET "TARGET=%SAVEDIR%\XP.User.Documents.rar"
SET "FILES=%DIRUSER%\Eigene Dateien\*"      
SET "EXLUCDE=%DIRUSER%\Documents\CDs" 
call:funcBackup "%TARGET%" "%FILES%" "%EXLUCDE%"
goto :eof

:funcBackup
    SET "TARGET=%~1"
    SET "FILES=%~2"
    SET "EXCLUDE=%~3"
    echo."%PACKER% a -r -x"%EXCLUDE%" "%TARGET%" "%FILES%"
    ::call %PACKER% a
goto :eof