How to set value of %%~nm to a variable.
[ie] when I try to set it like Set "var=%%~nm" and echo %var% .Output is giving empty string
I am facing this issue for all values which has ~.
Kindly provide a solution .
2 Answers
echo %var% should work fine when used outside the for loop. When you want to echo a variable inside a for loop, you have to enable delayed expansion and use !var! (variable is expanded at runtime) instead of %var% (variable is expanded at parsetime):
@echo off
setlocal EnableDelayedExpansion
for %%m in (*) do (
set "var=%%~nm"
echo !var!
)
echo %var%
endlocal
If you want to compare a variable to a string, you have to put either both between quotes or none:
if %var%==string ...
or
if "%var%"=="string" ...
Otherwise you'd be comparing string=="string", which are obviously not equal.
4 Comments
user2545157
I want to use the value of !var! for comaprision For Eg: If !var!=='Name' Echo name else echo 'Number'. Iam not able to do the comapriosn in If statemtn if I use !var!.Sorry to ask thiis Im new to Dos scripting
Ansgar Wiechers
See updated answer. If that doesn't help, update your question with your actual code. This has nothing to do with DOS, BTW.
user2545157
@echo off setlocal EnableDelayedExpansion for %%m in (*) do ( set "var=%%~nm" If "!var!"=="Name" echo !var!) endlocal.when i m comparing like this this is not working I want to compare in the fforr lloooop onnlly
Ansgar Wiechers
"It's not working" is an insufficient problem description. Please update your question with your actual code, sample input and the expected output.