0

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 2

2

try this (new variables can't be used in the same for loop without delayed expansion:

for %%m in (*) do call:doit "%%~nm"
goto:eof

:doit
set "var=%~1"
echo %var%
goto:eof
Sign up to request clarification or add additional context in comments.

Comments

0

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

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
See updated answer. If that doesn't help, update your question with your actual code. This has nothing to do with DOS, BTW.
@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
"It's not working" is an insufficient problem description. Please update your question with your actual code, sample input and the expected output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.