jmituzas
jmituzas

Reputation: 603

.bat If Then Statement

I need help with writing a batch script for

if file newfile.txt exists
then  del "InDesignData.txt"
ren "newfile.txt" "InDesignData.txt"

Upvotes: 3

Views: 39956

Answers (4)

James K
James K

Reputation: 4055

You could do it several ways, the cleanest methods would be:

On a single line:

if exist newfile.txt del "InDesignData.txt" & ren "newfile.txt" "InDesignData.txt"

On separate lines:

if exist newfile.txt del "InDesignData.txt"
if exist newfile.txt ren "newfile.txt" "InDesignData.txt"

Or using ( )

if exist newfile.txt (
    del "InDesignData.txt"
    ren "newfile.txt" "InDesignData.txt"
)

Using the brackets is an improvement over using GOTO because it is much cleaner code. (It's just not usually what I think of first because I learned BATCH under MS-DOS.)

I can't think of a reason to use the GOTO statement, unless you are using and ancient version of Windows. And in THAT case I would only use the GOTO statement if what you are testing for (in this case if newfile.txt exists) is changed (say, deleted in this case) in the first IF statement. The GOTO statement tends to make reading the script later more difficult.

Upvotes: 4

echobravo
echobravo

Reputation: 393

One way you can do this is to is to have if statements and labels for both error and success and use ECHO to debug it... my example here has to do with directories, but surely you can adapt for you file deletion/creation needs:

    ECHO Cleaning up folders...
    if exist %myDir% goto deleteFolder
    goto createNewDir

    :deleteFolder
    echo Deleting %myDir%
    RMDIR %myDir% /S /Q
    IF ERRORLEVEL 1 GOTO Error


    :createNewDir
    mkdir %myDir%
    IF ERRORLEVEL 1 GOTO Error
    goto Done

    :error
    echo something went wrong
    goto End

   :Done
    echo Success!

   :End

HTH, EB

Upvotes: 0

Rudu
Rudu

Reputation: 15892

You can use simple curved brackets (also supporting else!)

@echo off
IF EXIST newfile.txt (
del "InDesignData.txt"
ren "newfile.txt" "InDesignData.txt"
)

With else:

@echo off
IF EXIST newfile.txt (
del "InDesignData.txt"
ren "newfile.txt" "InDesignData.txt"
) else (
echo Making tea
)

Upvotes: 10

stacker
stacker

Reputation: 68962

if not exist newfile.txt goto skip
del "InDesignData.txt"
ren "newfile.txt" "InDesignData.txt"
:skip

Upvotes: 8

Related Questions