开发者

.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" "InDesign开发者_如何学运维Data.txt"


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
)


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜