0

I am attempting to check whether the first argument passed to the file is python, if so I would like to go to a particular block. It feels like I'm misunderstanding something about the way batch files test for equality.

@echo off
IF ("%1"=="python") (GOTO py) ELSE (echo %1)

GOTO end
:py
IF ("%2"=="") (echo ) ELSE (.\Programs\Anaconda\condabin\conda.bat activate %2)
.\Programs\Anaconda\python
GOTO end
:nextpy

:end

The output of this file when called D:>launcher.bat python is:

python

I expect it to instead open a python shell.

Gerhard
  • 18,114
  • 5
  • 20
  • 38
  • 2
    Open a [command prompt](https://www.howtogeek.com/235101/), run `if /?` and read the output help for the command __IF__. Next run also `call /?` as read about `%1` and `%~1` to reference fist argument of a batch file which could be already in double quotes, but could be also without double quotes. Then read my answer on [Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files](https://stackoverflow.com/a/47386323/3074564) explaining very detailed how a string comparison is done by __IF__ respectively Windows command processor. – Mofi Jul 12 '20 at 18:23
  • 1
    I suggest to modify `IF ("%1"=="python") (GOTO py) ELSE (echo %1)` to `IF /I "%~1" == "python" (GOTO py) ELSE (echo(%1)` with looking on where `(` and `)` are used and where are space characters placed on this command line. The __ELSE__ branch could be also just `ELSE echo(%1`. I suggest `IF not "%~2" == "" .\Programs\Anaconda\condabin\conda.bat activate %2` for the second __IF__ condition. See also DosTips forum topic: [ECHO. FAILS to give text or blank line - Instead use ECHO/](https://www.dostips.com/forum/viewtopic.php?f=3&t=774) – Mofi Jul 12 '20 at 18:29
  • 1
    `(` between `echo` and `%1` makes sure that echo status is not output by Windows command processor if the batch file is called without any argument string. – Mofi Jul 12 '20 at 18:33
  • just to clarify: `("%1"` will never be equal to `"python")` the parentheses here are part of the strings, not part of any syntax. – Stephan Jul 13 '20 at 18:12

1 Answers1

0

You don't need all the goto statements as you can run the code inside of the parenthesized code blocks. but your main problem is the fact that you placed if statements inside parenthesis:

Here is an example of how to run the code inside of the blocks instead of using goto

@echo off
if "%~1"=="" echo You have not added any parameters.
if /i "%~1"=="python" (
  if not "%~2"=="" (
          echo .\Programs\Anaconda\condabin\conda.bat activate %~2
   ) else (
          echo empty parameter "%%2"
      )
   ) else (
          if /i "%~1"=="perl" (
          echo you chose perl
   )
)

Note that I used the /I switch with the if statement simply to match case insensitive words. So it will accept PYTHON PyThoN python etc.

Gerhard
  • 18,114
  • 5
  • 20
  • 38