Check if command is available in batch file

I am writing a batch file for Windows and using the 7z (7-Zip) command. I posted it in PATH. Is there a relatively easy way to check if a command is available?

+7
source share
4 answers

Attempting to execute 7z.exe will return %errorlevel% from 9009 if the command is not found. You can check it out.

 7z.exe if %errorlevel%==9009 echo Command Not Found 

Note This solution is suitable for this particular 7zip using 7zip and probably for many others. But, as a rule, executing a command to determine if it can be potentially dangerous. Therefore, make sure that you understand the effect of executing the command being tested, and use this approach as you see fit.

-2
source

Do not execute the command to check its availability (that is, found in the PATH environment variable). Use where instead:

 where 7z.exe >nul 2>nul IF NOT ERRORLEVEL 0 ( @echo 7z.exe not found in path. [do something about it] ) 

>nul and 2>nul prevent the display of the result of the where command for the user. Direct execution of the program has the following problems:

  • It’s not immediately clear what the program does
  • Unintended side effects (file system changes, sending emails, etc.)
  • Resource intensive, slow startup, I / O lock, ...

You can also define a procedure to help users verify that their system meets the requirements:

 rem Ensures that the system has a specific program installed on the PATH. :check_requirement set "MISSING_REQUIREMENT=true" where %1 > NUL 2>&1 && set "MISSING_REQUIREMENT=false" IF "%MISSING_REQUIREMENT%"=="true" ( echo Download and install %2 from %3 set "MISSING_REQUIREMENTS=true" ) exit /b 

Then use it like:

 set "MISSING_REQUIREMENTS=false" CALL :check_requirement curl cURL https://curl.haxx.se/download.html CALL :check_requirement svn SlikSVN https://sliksvn.com/download/ CALL :check_requirement jq-win64 jq https://stedolan.imtqy.com/jq/download/ IF "%MISSING_REQUIREMENTS%"=="true" ( exit /b ) 
+21
source

Yup,

 @echo off set found= set program=7z.exe for %%i in (%path%) do if exist %%i\%program% set found=%%i echo "%found%" 
+1
source

Yes, open a command window and enter "7z" (I assume this is the name of the executable file). If you receive an error message stating that the command or operation was not recognized, you know that the path operator has a problem, but otherwise it is not.

-1
source

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


All Articles