SeaStar
SeaStar

Reputation: 1237

How to know whether a command is executed successfully via a batch file?

For example, in a batch file, I typed the command below:

xcopy C:\fileA.txt D:\Dir\ /y /d

It will fail absolutely if there was not a file called fileA.txt. But I want to know if it fails, then output some messages to user. How can I do this?

Any help will be grateful, thanks!

Upvotes: 3

Views: 18075

Answers (4)

Davide
Davide

Reputation: 2124

Just use the following structure:

command > nul 2> nul && (
    echo Success
    REM can be multi line
) || (
    echo Error
    REM can be multi line
)

Upvotes: 0

sparrowt
sparrowt

Reputation: 2968

I found the accepted answer didn't work but this did:

if %ERRORLEVEL% neq 0 goto ERR

Upvotes: 2

matt forsythe
matt forsythe

Reputation: 3912

I think what you are interested in is "error levels". See http://www.robvanderwoude.com/errorlevel.php. Basically, in your batch file, you can check the status code of the command (similar to Unix or Linux) by saying

IF ERRORLEVEL 1 <do something>
IF ERRORLEVEL 2 <do something>

where 1 and 2 are possible values of the status code returned by the last program executed. You can also do something like

echo %ERRORLEVEL%

to print out the status code, but note that it does not always behave like a "normal" environment variable. One thing that makes it different is that it does not show up with the "set" command.

Upvotes: 3

shinjin
shinjin

Reputation: 3027

Most commands/programs return a 0 on success and some other value, called errorlevel, to signal an error.

You can check for this in you batch for example by

if not errorlevel 0 goto ERR

xcopy errorlevels:

0 - All files were copied without errors

1 - No files were found to copy (invalid source)

2 - XCOPY was terminated by Ctrl-C before copying was complete

4 - An initialization error occurred.

5 - A disk-write error occurred.

[1] http://m.computing.net/answers/dos/xcopy-errorlevels/7510.html

Upvotes: 12

Related Questions