I have a bat script for which I need to provide a parameter. If that parameter equals, "my-test1", it will execute a script. If that parameter equals "my-test2", it will execute another one. If the parameter does not exist in any of the if/elseif, return code 1.
How could I achieve this? Please find below what I've tried so far.
if "%~1" == "my-test1" (
python.exe mypath\my_test1.py
)
elseif "%~1" == "my-test2" (
python.exe mypath\my_test2.py
)
else
EXIT WITH AN EXECUTION CODE 1
CodePudding user response:
else
and if
are separate keywords. Put a space between them.
EXIT WITH AN EXECUTION CODE 1
should be exit /b 1
AND else
must be on the same physical line as the )
closing the true conditional processing
AND else
must either be followed by some command(s) or (
and commands on the next line(s)
ie.
if "%~1" == "my-test1" (
python.exe mypath\my_test1.py
) else if "%~1" == "my-test2" (
python.exe mypath\my_test2.py
) else EXIT /b 1
Use if /i
to do a case-insensitive match
CodePudding user response:
If your scripts are genuinely numerically named, you can use choice
:
@echo off
echo %1|choice /c 12 /m "my-test1 mytest-2"
python.exe "mypath\my_test%errorlevel%.py"
This will prompt the user if you run the file as is filename.cmd
or it can be used with paramaters filename.cmd 1
if however you want to retain the current format to use specific input such as filename.cmd my-test1
no need for if
and else
.
@echo off
if "%~1" == "my-test1" python.exe "mypath\my_test1.py"
if "%~1" == "my-test2" python.exe "mypath\my_test2.py"