Search code examples
batch-fileproperties-file

How to read properties file from batch file


I have a long test.properties file that contains the following at the very top:

property1=cheese
property2=apple
property3=bread

# many more properties

I can read those properties from the command line by changing the working directory to the one containing test.properties and running the following command:

> FOR /F "tokens=1,2 delims==" %A IN (test.properties) DO
    IF "%A"=="property1" SET firstitem=%B
> FOR /F "tokens=1,2 delims==" %A IN (test.properties) DO
    IF "%A"=="property2" SET seconditem=%B

> echo %firstitem%
cheese
> echo %seconditem%
apple

However, when I try to put this code in a batch file stored in the same directory, it fails and I cannot work out why:

FOR /F "tokens=1,2 delims==" %A IN ("%~dp0\test.properties") DO 
    (IF "%A"=="property1" SET firstitem=%B)
FOR /F "tokens=1,2 delims==" %A IN ("%~dp0\test.properties") DO
    (IF "%A"=="property2" SET seconditem=%B)

Running the batch file from the command line gives me this:

> "C:\folder\testbatch.bat"
~dp0\test.properties") DO IF "B was unexpected at this time.

What can I do to read the properties using the batch file, so that they are stored in variables that can be used in the rest of the script?

EDIT: Problem solved; working code below.

FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%~dp0\test.properties") DO 
    (IF "%%A"=="property1" SET firstitem=%%B)
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%~dp0\test.properties") DO
    (IF "%%A"=="property2" SET seconditem=%%B)

Solution

  • There's two problems here:

    1. In the batch file version you need two percent signs for the iterator variables.
    2. In the batch file version you erroneously put quotes around the file name, causing the string itself to be tokenized, not the contents of the file specified by the string. Update: @Stephan correctly noted the use of the usebackq modifier for a more general solution. But since you're talking about "batch file stored in the same directory", you might as well drop the path prefix %~dp0 altogether.

    Corrected version:

    @ECHO OFF
    FOR /F "tokens=1,2 delims==" %%A IN (test.properties) DO (
        IF "%%A"=="property1" SET firstitem=%%B 
    )
    FOR /F "tokens=1,2 delims==" %%A IN (test.properties) DO (
        IF "%%A"=="property2" SET seconditem=%%B
    )
    ECHO %firstitem%
    ECHO %seconditem%
    

    Returns:

    cheese
    apple