Kelsey R.
Kelsey R.

Reputation: 55

If statement in batch script isn't working?

I have a batch script which when given the input "edit", should then echo "hello" as a sort of debug and open the batch scripts file in notepad. However for some inexplicable reason the script will not respond to the if statement no matter what. How do I get it to respond to the "edit" input?

REM @ECHO OFF
cd/
cd projects\py_test
ECHO Use this batch script to lauch Python modules living in "C:\Projects\py_test\" ONLY.
ECHO.
SET /P name="Type file name with file extension .py to start or type EDIT to edit this .bat: "
REM @ECHO OFF
cmd /k IF %name%==edit GOTO EDIT
REM IF EXIST %name% py %name%
REM IF NOT EXIST %name% echo  [101mERROR: The requested file could not be found.  Make sure the file exists in "C:\Projects\py_test\" and that the filename includes the ".py" extension.[0m 
@ECHO OFF
:EDIT
ECHO HELLO
notepad projects-py_test-dot_start.bat`

Upvotes: 0

Views: 96

Answers (1)

user7818749
user7818749

Reputation:

Firstly, why all the REM @ECHO OFFs? It looks ugly, especially when they are all caps.

Then, you want to run cmd /k for an if statement for no real reason? With the variable name you need to preferbly enclose the if statement variables in double quotes to eliminate possible whitespace:

@echo off
cd /d "C:\projects\py_test"
echo Use this batch script to lauch Python modules living in "C:\Projects\py_test\" ONLY.
echo/
set /p name="Type file name with file extension .py to start or type EDIT to edit this .bat: "
if defined name set "name=%name:"=%"
if /i "%name%"=="edit" goto edit
goto :EOF
:edit
echo hello
notepad echo "%~f0"

but by guessing that you simply want to launch a python script if it exists, else edit itself, then I would instead do this version without the labels. It simply checks if the name typed exists (hoping the user typed the full script with extension) else, we add the extension test in case the user typed only the name and not extension.:

@echo off
cd /d "C:\projects\py_test"
echo Use this batch script to lauch Python modules living in "C:\Projects\py_test\" ONLY.
echo/
set /p name="Type file name with file extension .py to start or type EDIT to edit this .bat: "
 if defined name set "name=%name:"=%"
 if /i "%name%"=="edit" notepad "%~f0"
 if exist "%name%" (
             python "%name%"
    ) else (
            if exist "%name%.py" (
                      python "%name%.py"
       ) else (
             echo "%name%" does not exist
     )
  )

Upvotes: 1

Related Questions