0

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
    )
)
Amesh Fernando
  • 487
  • 4
  • 8
  • 2
    A variable is displayed like this `%variablename%`, not like this `%%variablename`, and your `For /L` loop is incorrectlly wirtten. Please open a Command Prompt window, type `for /?`, and press the `[ENTER]` key, then do the same with `set /?`. – Compo Dec 01 '21 at 00:42
  • 1
    The code corrections look good and it should work now but, I don't see the point of your code. Your code will execute in less than a half second. What is the point of check for a file three times that quickly? – Squashman Dec 01 '21 at 00:50
  • yes, the previous code worked. But I want to update the fi variable during the for loop, the if condition fails – Amesh Fernando Dec 01 '21 at 00:59
  • 3
    If that's the case, you'll need to enable delayed expansion, _(using `SetLocal EnableDelayedExpansion`)_, and expand your variable like this, `!variablename!`. – Compo Dec 01 '21 at 01:12

1 Answers1

0

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 setting 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.

Gerhard
  • 22,678
  • 7
  • 27
  • 43