Reputation: 5
Example:
set mydir=%CD%
echo %CD%
C:\Stuff\More Stuff\Lots of Stuff
So how should the variable be used? Usually the entire path could be encased in quotes, but what about the variable?
for /f %G in (%mydir%\file.txt) DO (echo %G)
Upvotes: 0
Views: 646
Reputation: 38613
Use either this:
set mydir="%CD%"
echo %mydir%
or in the loop case
set "mydir=%CD%"
echo "%mydir%"
for /f "usebackq delims=" %%G in ("%mydir%\file.txt") DO echo %%G
although I would see no benefit in not using
echo "%__CD__%"
for /f "usebackq delims=" %%G in ("%__CD__%file.txt") DO echo %%G
Why set something you don't need?
Upvotes: 0
Reputation: 34909
The key is proper quotation. The following syntax is the only secure way to set a variable -- supposing the value does not contain quotation marks on its own, and the command extensions are enabled (which is the default anyway, and there are almost no situations where command extensions disturb):
set "myDir=%CD%"
The quotation marks do not become part of the value that way.
To use the value in a for /F
loop as you try to do in your question, use this (remember to double the %
signs in a batch file):
for /F "usebackq" %G in ("%myDir%\file.txt") do (echo %~G)
The option usebackq
is now required in order for the quoted path not to be treated as a literal string.
EDIT: This is the former answer before I noticed the /F
option at the for
command.
I do not remove it because that might be helpful in case a standard for
loop is used:
To use the value in a for
loop as you try to do in your question, use this (remember to double the %
signs in a batch file):
for %G in ("%myDir%\file.txt") do (echo %~G)
The ~
modifier removes the quotation marks from the value.
To ensure that the expanded value is always surrounded by quotation marks, use this:
for %G in ("%myDir%\file.txt") do (echo "%~G")
In general, paths should always be quoted in order to avoid trouble with white-spaces and also other special characters. For example, %myDir%
holds a path like D:\Docs & Data
, the command line echo D:\Docs & Data
echoes the string D:\Docs
SPACE and tries to execute a command named Data
, which does not exist (most probably), because the &
symbol has a special meaning, namely to concatenate two separate commands in one line. Quoting the path like echo "D:\Docs & Data"
avoids this problem (although the quotes are are returned too by echo
; but they are ignored by commands that accept path arguments, like cd
or copy
, for instance).
Upvotes: 1