Check whether command is available in batch file

蹲街弑〆低调 提交于 2020-01-03 08:59:41

问题


I'm writing a batch file for Windows and use the command 7z (7-Zip). I have put the location of it in the PATH. Is there a relatively easy way to check whether the command is available?


回答1:


An attempt to execute 7z.exe will return an %errorlevel% of 9009 if the command is not found. You can check that.

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

Note: This solution is viable for this specific 7zip use case, and likely for plenty of others. But as a general rule, executing a command to determine whether it's present could potentially be harmful. So make sure you understand the effect of executing the command you're checking for, and use your discretion with this approach.




回答2:


Do not execute the command to check its availability (i.e., 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]
)

The >nul and 2>nul prevent displaying the result of the where command to the user. Executing the program directly has the following issues:

  • Not immediately obvious what the program does
  • Unintended side effects (change the file system, send emails, etc.)
  • Resource intensive, slow startup, blocking I/O, ...

You can also define a routine, which can help users ensure 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 such as:

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.github.io/jq/download/

IF "%MISSING_REQUIREMENTS%"=="true" (
  exit /b
)



回答3:


Yup,

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



回答4:


Yes, open a command window and type "7z" (I assume that is the name of the executable). If you get an error saying that the command or operation is not recognised then you know the path statement has a problem in it somewhere, otherwise it doesn't.



来源:https://stackoverflow.com/questions/10686737/check-whether-command-is-available-in-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!