Determine if command is recognized in a batch file

Solution 1:

WHERE mycommand
IF %ERRORLEVEL% NEQ 0 ECHO mycommand wasn't found 

Solution 2:

The code below should always execute cleanly with no garbage output.

javac -version >nul 2>&1 && (
    echo found javac
) || (
    echo fail
)

Output:

found javac

The same code as a one-liner:

javaz -version >nul 2>&1 && ( echo found javac ) || ( echo fail )

Output:

fail

Note that the order of && and || seems to matter. Also, the command whose existence you are testing for needs to return with an errorlevel <= 0 for this to work. Hopefully the command has /? or --help arguments or, as with java, a version info command.

Solution 3:

The easiest way is to simply run the command, but that has other problems, of course, since maybe you don't want to have a random process started.

for %%x in (my_command.exe) do if not [%%~$PATH:x]==[] set MyCommandFound=1

is an alternative which searchs for the program in the paths listed by the %PATH% environment variable. It's essentially a pure batch version of which(1). It can be made better but essentially this is it.