Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

batch file: pass parameter with white spaces to function

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?

like image 782
Matthias Pospiech Avatar asked Jul 13 '11 20:07

Matthias Pospiech


2 Answers

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   
like image 75
jeb Avatar answered Oct 27 '22 12:10

jeb


Switching your arg calls in the function from %~1, %~2 and %~3 to %~f1, %~f2 and %~f3 respectively should do the trick. It'll pass the fully qualified path name for each arg.

More info: http://www.windowsitpro.com/article/server-management/how-do-i-pass-parameters-to-a-batch-file-

like image 39
Costa Avatar answered Oct 27 '22 12:10

Costa