sam
sam

Reputation: 1

Value assigned to the variable not working in batch script

Here is the logic I am trying to write. It needs to work on both Windows 7, Windows 2008 server and Windows 2012 server. I want to test the presence of a file (x.txt) and if it is not present, I want to create it. If the file x.txt is present, I want to create a temp file and compare them. If they both are equal, del temp file. Otherwise, over-write x.txt.

The trouble is it complains ") was unexpected at this time." when executes the first IF NOT EXIST statement. Now if I use "%destFile%", it always says "The system cannot find the path specified." and runs writeOutputConf even if the file exists.

Again the FC command is not working!

What am I doing wrong? Pl help.

SET destFile="C:\Test Scripts\local\x.txt"
SET tmpFile="C:\Test Scripts\local\tmp.txt"
IF NOT EXIST %destFile% (
    call:writeOutputConf
) ELSE (
    call:writeTempConf  
    FC %destFile% %tmpFile%>NUL
    IF ERRORLEVEL 1 (
        ECHO files are not equal
        CALL:writeOutputConf
        DEL "%tmpFile%"
    ) ELSE (
    ECHO files are equal
    DEL "%tmpFile%"
    )   
)
:: Functions
:writeOutputConf
ECHO Hellow World>%destFile%
GOTO:EOF

:writeTempConf
ECHO Hellow World>%tmpFile%
GOTO:EOF

Upvotes: 0

Views: 29

Answers (1)

Magoo
Magoo

Reputation: 80203

Two glaring problems.

You are confusing this:

SET destFile="C:\Test Scripts\local\x.txt"

and

SET "destFile=C:\Test Scripts\local\x.txt"

The first sets destfile to a quoted string + any trailing spaces that may be present on the line.

The second ensures that any trailing spaces are not included and assigns an unquoted string.

Personally, I find the second more flexible.

In your code, you are assigning quoted strings, so

FC %destFile% %tmpFile%>NUL

will correctly compare the two files. Each must be a quoted string since the paths contain spaces.

I would write that as

FC "%destFile%" "%tmpFile%">NUL

using unquoted strings.

So far, just a matter of convention, however you go on to use

    DEL "%tmpFile%"

which, since you are using quoted strings is evaluated to

    DEL ""thetempfilename""

so the quotes are not necessary...

Moral: pick a convention and stick to it.

The second problem is that batch has no concept of "end of procedure" other than physical end-of-file. consequently,

    )   
)
:: Functions
:writeOutputConf
ECHO Hellow World>%destFile%

charges merrily on through the label :writeOutputConf and creates the file regardless when the if statement is complete.

  • add a GOTO :EOF after that last close-parenthesis to stop the fall-through to the subroutines.

Upvotes: 2

Related Questions