Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether command is available in batch file

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?

like image 640
rynd Avatar asked May 21 '12 14:05

rynd


People also ask

What is %% A in batch file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

How can I see the code of a batch file?

To open the BAT file in Notepad, right-click it and choose Show more options > Edit from the menu (or just Edit in some Windows versions). You might find it helpful to use more advanced text editors that support syntax highlighting when editing a BAT file.


2 Answers

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
)

PowerShell:

On PowerShell, the Get-Command cmdlet can be considered to be the equivalent of cmd's where.exe.

Get-Command <cmd>
IF ($? -ne $true)
{
    Write-Host "<cmd> not found in path"
    # Do something about it
}
like image 113
Sachin Joseph Avatar answered Oct 07 '22 21:10

Sachin Joseph


Yup:

@echo off
set found=
set program=7z.exe
for %%i in (%path%) do if exist %%i\%program% set found=%%i
echo "%found%"
like image 36
nullpotent Avatar answered Oct 07 '22 20:10

nullpotent