2

On linux you can use command; how can I determine if a command exists on Windows?

where does not appear to work on cd; I'm looking for something that will work even on the built-in commands.

Community
  • 1
  • 1
mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • 2
    `help` works on internal commands, `where` on external ones. – Harry Johnston Dec 10 '14 at 03:09
  • @HarryJohnston How would I determine if its internal or external then? – mpen Dec 10 '14 at 03:23
  • @HarryJohnston Is there a way to do it in one statement? The exit code for `help` seems to be inverted, so `help CMD || where CMD` won't work. – mpen Dec 10 '14 at 03:38
  • How about `help CMD && where CMD` then? – Harry Johnston Dec 10 '14 at 03:39
  • @HarryJohnston Thought about that, but that won't work either. It either needs to be `not(help CMD) || where CMD` or `help CMD && not(where CMD)`. What you wrote isn't equivalent. – mpen Dec 10 '14 at 03:44
  • Oh, you're trying to determine whether or not either option succeeded? They're not really intended for scripted use (I can't imagine what you're trying to achieve!) but it shouldn't be too hard to come up with something. Is this in a batch script, or some other context? – Harry Johnston Dec 10 '14 at 05:05
  • @HarryJohnston It's going into a PHP script. I want to check if a few things are installed so that I can configure the environment correctly. That's my specific use-case; now I'm just looking for a generic solution so that I can make a function out of it. – mpen Dec 10 '14 at 05:32

1 Answers1

4

Personally, I'd probably run each command separately, and do the logic in PHP. (You might also want to consider whether it is necessary to test for the existence of the internal commands at all; they haven't really changed much in the last couple of decades.)

However, this should work:

cmd /c "(help FOO > nul || exit 0) && where FOO > nul 2> nul"

This will return 0 if the command FOO is found, 1 if it is not.

Harry Johnston
  • 35,639
  • 6
  • 68
  • 158