1 - Missing spaces
If %Running% EQU 0 (...
^ This space is needed
2 - In batch files lines of code are executed one after the other unless one command changes this behaviour. You can iterate with for
, jump with goto
, call subroutines with call
, leave the batch, the subroutine or the console with exit
, ... but a label will not break the execution. After your if %Running% EQU 1 ...
there isn't anything that prevent execution to continue into the code following code it none of the if
tests find a coincidence. So, if the set /p
does not retrieve 0
or 1
the code after :ProgramNotRunning
will be always executed.
3 - Missing/empty file. If IsRunning.txt
can not be found or it is empty (or at least the first line is empty) or if it does contain an unexpected value, the if
lines will fail. The code executed is
file missing : if EQU 0 (
line/file empty : if EQU 0 (
bad data : if this is a test EQU 0 (
All this cases will cause the line to be considered an error and the execution will be canceled.
@echo off
setlocal enableextensions disabledelayedexpansion
rem Retrieve running state
set "Running="
if exist "IsRunning.txt" (
set /p "Running=" < "IsRunning.txt"
)
IF "%Running%" EQU "0" goto ProgramNotRunning
IF "%Running%" EQU "1" goto ProgramRunning
rem As there is no valid data, assume the program is not running
:ProgramNotRunning
echo program starting
>"IsRunning.txt" (echo 1)
goto :eof
:ProgramRunning
echo program already running
goto :eof
Why >"IsRunning.txt" (echo 1)
? Just to be sure there are no aditional spaces after the 1
that will be included in the output (as happens with your code), retrieved when the line is readed from the file and causing the if
to fail
if "1 " EQU "1" ( ... This will be evaluated to false
And this still leaves cases where the data retrieved can make the code fail. For a 0/1
test, it is easier to not read the file, just test for presence of the file. If the file exist, the program is running, else it is not running.