user736893
user736893

Reputation:

batch file variable doesn't work inside if statement, even with delayed expansion?

I'm writing a batch file that will modify an input file but only if the filename contains -source.

This works:

@echo off
@setlocal ENABLEDELAYEDEXPANSION

set fn=%1
echo Checking %fn%...
set outfile=%fn:-source=%
if not x%fn:-source=%==x%fn% (
    echo Output to %outfile%
)

but this does not:

@echo off
@setlocal ENABLEDELAYEDEXPANSION

set fn=%1
echo Checking %fn%...
if not x%fn:-source=%==x%fn% (
    set outfile=%fn:-source=%
    echo Output to %outfile%
)

In the second case, it simply outputs "Output to" with no file name. How can I fix this?

Upvotes: 0

Views: 48

Answers (1)

Compo
Compo

Reputation: 38579

Here's your second script again, with my answer from my comment and some additional improvements with regard double quoting.

@Echo Off
If "%~1"=="" Exit/B
Set "fn=%~1"
Echo Checking %fn%...
SetLocal EnableDelayedExpansion
If Not "x%fn:-source=%"=="x%fn%" (
    Set "outfile=%fn:-source=%"
    Echo Output to !outfile!
)

As an additional note, if "x%fn:-source=%" does equal "x%fn%" there is no need to use the If, (making a substitution which doesn't alter the value is harmless).

@Echo Off
If "%~1"=="" Exit/B
Set "fn=%~1"
Echo Checking %fn%...
Set "outfile=%fn:-source=%"
Echo Output to %outfile%

Upvotes: 1

Related Questions