开发者

windows batch: react to command not found

i want to write a simple batch script, that calls a certain exe, but if this one is not found, it should c开发者_运维知识库all another exe.

so in pseudocode

set file=c:\path\tool.exe
if(fileexists(file))
{
    call file
}
else
{
    call c:\somethingelse.exe
}

thanks!


You could use ERRORLEVEL to check if the call executed successfully.

call file.exe
IF ERRORLEVEL 1 other.exe

This will work for executables that are in the path and you don't know the exact location. It will print an error message though.


To closely resemble the pseudo-code posted in the original question:

set FILE1=c:\path\tool.exe
set FILE2=c:\path\to\other\tool.exe
if exist "%FILE1%" (
    %FILE1%
) else (
    %FILE2%
)

As Joey pointed out this actually is the opened form of:

%FILE1% || %FILE2%

but I don't agree. The former runs FILE2

  1. when FILE1 not exists, or
  2. exists but failed.

It also prints an additional error message when a file can't be executed (mostly because it wasn't found or access is prohibited). To suppress this message use:

(%FILE1% || %FILE2%) 2>nul

For example

> (echo a || echo b)
a
> (echoa || echo b) 2>nul
b

To suppress all output, and just arrange it that any of both files is run:

(%FILE1% || %FILE2%) 1>&2 2>nul

or:

((%FILE1% || %FILE2%) 1>&2 2>nul) || echo both have failed

as in:

> ((echo a || echo b) 2>nul) || echo both have failed
a
> ((echoa || echo b) 2>nul) || echo both have failed
b
> ((echoa || echob) 2>nul) || echo both have failed
both have failed


Perhaps something like this might work?

set FILE=whatever.exe
IF EXIST %FILE% GOTO okay

:notokay
echo NOT FOUND
GOTO end

:okay
echo FOUND
%FILE%

:end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜