I have looked through a few of the questions on here and I was unable to find what I was looking for. Hopefully I can get some clarification on this.. I have the following Batch Code Block:
:CommandCheck
If Exist java -version (goto start)Else
(echo !!Java not installed!! Installing supported version now)
goto install
But when I run this, it just closes the command prompt. I am trying to get it to test a certain command and if it fails to load, it goes to another part of the script and if it does exist, it goes elsewhere. I have tested various methods mentioned here and else where but I cannot seem to get the working formula.
答案 0 :(得分:1)
First off, your logic does not require an ELSE:
:CommandCheck
If exist "someFile" goto start
echo !!Java not installed!! Installing supported version now
goto install
But I don't think you are attempting to check for the existence of a file. Instead you are attempting to run the command java -version
, and you want to goto start if that command was successful, and print a message and goto install if it failed.
You can use the &&
operator to conditionally execute a command if the prior command succeeded. There is a coralary ||
to execute a command if the prior command failed.
someCommand && echo someCommand succeeded || echo someCommand failed
You only need one or the other. I also assume you do not need to see the ouput (or error message) of the java -version
test.
:CommandCheck
java -version >nul 2>nul && goto start
echo !!Java not installed!! Installing supported version now
goto install
If you should ever want to truly use IF ELSE with parentheses, there are a couple important syntax rules
Here is an example
if exist "someFile" (
echo someFile exists
) else (
echo someFile does NOT exist
)
It can all be put on one line
if exist "someFile" (echo someFile exists)else (echo someFile does NOT exist)
The following fails because the opening parentheses are not preceded by a space, so "someFIle"(
and else(
are treated as tokens, which cannot work.
if exist "someFile"(echo someFile exists)else(echo someFile does NOT exist)
The following fails because the parentheses must be on the same lines as IF and ELSE
if exist "someFile"
(echo someFile exists)
else
(echo someFile does NOT exist)
答案 1 :(得分:0)
Try adding a pause function at the end.
答案 2 :(得分:0)
It is worth mentioning that checking for a specific version of a certain piece of software is a varied and complex task, doubly so on Windows, and even more so with Batch scripting.
You could check for the exact path of the java executable, and assume it isn't installed if Windows can't find it.
:CommandCheck
if not exist "c:\path\to\java.exe" (goto Install)
goto Start
Also:
Check out http://www.robvanderwoude.com/ and http://ss64.com/nt/ for more info on learning batch scripting. And Stack Overflow of course :)