I am trying to make a if statement for a CLI i am making in batch. this is the code
if "%command%" == "browser"(
echo Warning, this will only change the default broswer for this session
echo What would you like the default browser to be changed to?
set /p browserdefault=
)
I want it to check "browserdefault" and see if it is chrome, edge or a diffrent broswer if it is none of those it should say "error, invalid broswer."
is there any way for there to be a if statement inside of the already existing if statement? like if %browserdefault% is "chrome" start C:%username%\filepath\tochrome?
I tried many diffrent ways but none of them seems to work
CodePudding user response:
What you are trying to do is right, noble and good. However, this is Windows batch. The ordinary rules of style & good taste do not apply.
You should not try to nest other statements inside a batch command. There are times this will appear to work, but (based on a number of factors, such as a poorly considered logical condition, or even different input strings!) will occasionally cause the block to fail miserably. This will set you up for a world of painful debugging.
The suggestion in the comments to search for menu
is a good one. This should lead you to code that will have (what looks like) many unnecessary & unrelated blocks, all sprinkled with horrible goto
s. Just... it's fine. This is Windows batch. It will work, it will be reliable. Try not to think about the style too much.
There are some example menus in this excellent Q&A:
(as noted in at least one answer there, when using the naive if ERRORLEVEL 1
, this will actually check if the number is less than or equal, Using if "1" == "%ERRORLEVEL%"
or similar totally avoids this pitfall).
CodePudding user response:
As pointed out in the other answer this is Windows batch. I do not know a way of nested if statements.
I would use call
statements to get rid of the nested if statements like this:
:getCommand
set /P command=Enter command:
call :%command%
goto :getCommand
:browser
set /P browserdefault=Enter browser:
if not "%browserdefault%"=="chrome" if not "%browserdefault%"=="edge" echo error, invalid broswer.
goto :eof