Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read environment variables from file in Windows Batch (cmd.exe)

I'm trying to read variables from a batch file for later use in the batch script, which is a Java launcher. I'd ideally like to have the same format for the settings file on all platforms (Unix, Windows), and also be a valid Java Properties file. That is, it should look like this:

setting1=Value1
setting2=Value2
...

Is it possible to read such values like you would in a Unix shell script? The could should look something like this:

READ settingsfile.xy
java -Dsetting1=%setting1% ...

I know that this is probably possible with SET setting1=Value1, but I'd really rather have the same file format for the settings on all platforms.

To clarify: I need to do this in the command line/batch environment as I also need to set parameters that cannot be altered from within the JVM, like -Xmx or -classpath.

like image 576
Martin Probst Avatar asked Oct 24 '08 07:10

Martin Probst


People also ask

How can I see environment variables in CMD?

Select Start > All Programs > Accessories > Command Prompt. In the command window that opens, enter set. A list of all the environment variables that are set is displayed in the command window.

How do I read all environment variables?

The printenv command list the values of the specified environment VARIABLE(s). If no VARIABLE is given, print name and value pairs for them all. printenv command – Print all or part of environment. env command – Display all exported environment or run a program in a modified environment.

What does %1 do in CMD?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.


1 Answers

You can do this in a batch file as follows:

setlocal
FOR /F "tokens=*" %%i in ('type Settings.txt') do SET %%i
java -Dsetting1=%setting1% ...
endlocal

This reads a text file containing strings like "SETTING1=VALUE1" and calls SET to set them as environment variables.

setlocal/endlocal are used to limit the scope of the environment variables to the execution of your batch file.

The CMD Command Processor is actually quite powerful, though with a rather byzantine syntax.

like image 64
Joe Avatar answered Oct 06 '22 08:10

Joe