StuAlex
StuAlex

Reputation: 25

Odd behavior IF statement in Batch

I have a very simple Batch script that I'm working on

I'm considering implementing an updater with wget and version files locally and hosted on my server (yet I'm using Batch for some reason)

@echo off
for /f "tokens=* delims=" %%x in (version.txt) do set version=%%x 
if "%version%" == "1.0.0" (echo yes)

the text file it's referencing contains nothing but

1.0.0

Not even a new line. Echoing %version% gives me 1.0.0 in the console, but the if statement gets nothing.

Anyone wanna point out my error? I'm honestly clueless

Upvotes: 1

Views: 49

Answers (2)

rojo
rojo

Reputation: 24466

This is tricky. You have a space at the end of set version=%%x.

As a general point of scripting convention, whenever you set a variable to a string in a batch script, unless you have a specific reason not to do so, you should do set "variable=value" with the var=value pair quoted. That helps avoid problems like this. Your for /f line should end with set "version=%%x"

With the trailing space, you're basically saying if "1.0.0 " == "1.0.0", which is false.

As a side note, it is possible to fetch the content from your web server without using wget if you wish.

Upvotes: 2

Magoo
Magoo

Reputation: 80023

You appear to have a naughy space on the end of the set command.

Batch is sensitive to spaces in a SET statement. SET FLAG = N sets a variable named "FLAGSpace" to a value of "SpaceN"

The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. set /a can safely be used "quoteless".

Upvotes: 3

Related Questions