Search code examples
windowsbatch-filedouble-quotes

Troubles with double quotes and for /f


I am working on a batch-script and trying to make it work in directories containing spaces. In a particular line I do the following loop:

for /f "tokens=*" %%A in ('%~dp0fciv\fciv.exe -md5 %~dp1%FN%') do ...

If the current directory contains spaces the loop will fail to call the executable. Now I put it double quotes to fix it:

for /f "tokens=*" %%A in ('"%~dp0fciv\fciv.exe" -md5 %~dp1%FN%') do ...

This works fine until the parameter doesn't have spaces. Thus I need to put it in the double quotes too:

for /f "tokens=*" %%A in ('"%~dp0fciv\fciv.exe" -md5 "%~dp1%FN%"') do ...

But this doesn't work as expected. I made additional tests straight in the cmd:

for /F "tokens=* usebackq" %A in (`"c:\Test Folder\fciv\fciv.exe" -md5 "d:\Somefile"`) do echo %A
for /F "tokens=*" %A in ('"c:\Test Folder\fciv\fciv.exe" -md5 "d:\Somefile"') do echo %A

The error is: "c:\Test" not recognized as an internal or external command, operable program or batch file.

I also tried to leave the second double quotes out again:

for /F "tokens=*" %A in ('"c:\Test Folder\fciv\fciv.exe" -md5 d:\Somefile') do echo %A

That command does surprisingly what it should.

Why does the error happening and how to achieve the desired functionality?


Solution

  • Enclose entire command, within the backquotes, in quotes.

    C:\Users\User>for /F "usebackq tokens=*" %A in (`""C:\Users\Use r\Desktop\Editor\UEd\UEd.exe" -md5 "d:\Somefile""`) do echo %A
    

    Removing the last backquote may have worked if no parameters.