How to check if a command is available in the Windows shell?

To check if a command is available in the bash shell, I usually do:

command -v $COMMAND >/dev/null 2>&1 || { echo >&2 "Error: this script requires the command '$COMMAND' to be available" exit 1 } 

What is the equivalent in Windows?

+4
source share
1 answer

You can use something very similar

 %command% >nul 2>&1 || ( echo "Error: command not found" exit /b 1 ) 

Of course, this will actually execute the command, but most commands will not do anything without the correct parameters. If you want to be more confident, you can use %command% /? >nul 2&1 %command% /? >nul 2&1 . This will try to bring up the help page for the command without executing it.

Update: To avoid running the entire command, consider where.exe . It comes bundled with Vista and Windows 7. For other operating systems, you can download it. See this post on how to download it.

After that, you can run it with /Q to avoid additional output. A return code of 0 means that the command was found. I once discovered that the where command requires you to provide an extension.

At the other end, there is a lengthy discussion here about a batch β€œone-liner” that works without the specified extension (but does not actually execute when you specify the extension)

+2
source

Source: https://habr.com/ru/post/1434345/


All Articles