Lets say i want to copy a file from one location to another with this code:
@set FILE=%1
@set SCRDIR=C:\test dir
@set DSTDIR=%SCRDIR%\temp
for %%f in ("%SCRDIR%\%FILE%") do @(
echo Copying "%%f" to "%DSTDIR%"
copy "%%f" "%DSTDIR%"
)
The file exists:
C:\test dir>dir /b copyme.txt
copyme.txt
First i call the script with the name of the file as argument i want to copy:
C:\test dir>test.bat rename.txt
C:\test dir>for %f in ("C:\test dir\rename.txt") do @(
echo Copying "%f" to "C:\test dir\temp"
copy "%f" "C:\test dir\temp"
)
Copying ""C:\test dir\rename.txt"" to "C:\test dir\temp"
The system cannot find the file specified..
The above copy command fails, because of the extra quotes…
Now i call the script with the file name containing a wildcard * :
C:\test dir>test.bat copyme.*
C:\test dir>for %f in ("C:\test dir\copyme.*") do (
echo Copying "%f" to "C:\test dir\temp"
copy "%f" "C:\test dir\temp"
)
C:\test dir>(
echo Copying "C:\test dir\copyme.txt" to "C:\test dir\temp"
copy "C:\test dir\copyme.txt" "C:\test dir\temp"
)
Copying "C:\test dir\copyme.txt" to "C:\test dir\temp"
1 file(s) copied.
In the above example, where im using a wildcard, it works perfectly fine.
Can anyone explain this behaviour? Why does windows add extra quotes when im not using wildcards? Or is it omitting the extra quotes, because im using wildcards?
I have to quote the path\filename for the FOR loop in order to handle paths, which contain blanks, so omitting those is not an option.
when there are no wildcards,
forcommand doesn’t check if the file exists, so effectively treats its name as a string literal, quotes included.Just use
"%%~f"instead of"%%f"