Is there a way to get the value of a variable in an if exist command in batch scripts?
for example
@echo off
set fi=ab.txt
FOR /L %%i IN (0 1 2) DO (
set fi=a.txt
if exist %fi% (
echo do something
)
)
Is there a way to get the value of a variable in an if exist command in batch scripts?
for example
@echo off
set fi=ab.txt
FOR /L %%i IN (0 1 2) DO (
set fi=a.txt
if exist %fi% (
echo do something
)
)
In the current state your code is in, you require delayedexpansion
.
You however do not need to create the code block with the set
as you have and can therefore eliminate delayedexpansion
. The reason I say it is not needed is because of the unknown reason for set fi=ab.txt
and then set
ting it to something else in the loop. Therefore it is the same as this:
@echo off
set fi=ab.txt rem What is the purpose when you re`set` it right after?
set fi=a.txt
For /L %%i IN (0,1,2) DO (
if exist %fi% (
echo do something
)
)
If however your intension is to set a variable based on the for
loop metavariable values, then you would need delayedexpansion
. This example demonstrates the usage of the metavariables in the set
as well as transforming from %var%
to delayedexpansion
's !var!
.
@echo off
setlocal enabledelayedexpansion
set fi=ab.txt
FOR /L %%i IN (0,1,2) DO (
set "fi=a%%i.txt"
if exist !fi! (
echo do something
)
)
Final thought, if it is however like the first example, I am unsure as to why you want to check for something multiple times in a loop, unless you are expecting a file to land within milliseconds.