0

my bat file is located as follows

<app-root>\bin\myscript.bat

my text file containing the PID i am looking to extract is located here

<app-root>\log\pid.lock

@echo off

@REM declare the location of the PID file
set "PID_FILE=%~dp0..\log\pid.lock"

@REM the following works to read the PID
type "%PID_FILE%"

@REM but setting it to a variable does not work
if exist "%PID_FILE%" (
    set /p PID=<"%PID_FILE%"
    
    @REM this returns nothing ...
    echo The PID is: %PID%
) else (
    echo PID file not found: %PID_FILE%
)

the contents of my pid.lock file just contains a singular pid

8120

output:

PS C:\Users\ALilland\Documents\dev\app\bin> .\online.bat
8120The PID is: 

how can i extract my PID to a variable?

alilland
  • 2,039
  • 1
  • 21
  • 42
  • In addition to the duplicate, **1.** ```@Set "PID=" & Set /P PID=<"%~dp0..\log\pid.lock" 2>NUL```, **2.** ```@If Defined PID (Echo PID is: %PID%) Else Echo PID not found```. – Compo Mar 28 '23 at 17:26
  • i am totally not fluent in batch, so unfortunately im still sunk. – alilland Mar 28 '23 at 17:29
  • I gave you the entire replacement code for everything you posted. Alternatively, you could use this instead: **1.** ```@Set "PID=" & Set /P PID=<"%~dp0..\log\pid.lock" 2>NUL```, **2.** ```@If Not Defined PID (Echo PID not found.& %SystemRoot%\System32\timeout.exe /T 3 /NoBreak 1>NUL & GoTo :EOF)``` **3.** ```@Echo PID is: %PID%```, **4.** ```@Rem The rest of your code goes here.``` – Compo Mar 28 '23 at 17:35
  • You didn't really try to read the duplicate, understand it, and try anything, in the three minutes it took you to reply. The duplicate advises, **1.** `@Echo Off & SetLocal EnableDelayedExpansion`, **2.** `@Rem Declare the location of the PID file.`, **3.** `Set "PID_FILE=%~dp0..\log\pid.lock"`, **4.** `If Exist "%PID_FILE%" (Set /P "PID=" 0<"%PID_FILE%"`, **5.** `Echo The PID is: !PID!) Else Echo PID file, %PID_FILE%, not found.` – Compo Mar 28 '23 at 17:46
  • Also, if you want my advice, do not use the PowerShell Prompt, to run batch files. Open a Command Prompt window instead. – Compo Mar 28 '23 at 17:51

0 Answers0