2

I'm writing a script to start a java program on both Windows and Linux. It needs to use a config file as I will have both batch files (on Windows) and shell scripts (on Linux).

The config file (cmd.config):

CUSTOM_JAVA_HOME=""
JAVA_FLAGS="-server -Xmx2048M"

In my batch file, I load it like this:

if exist cmd.config for /F "delims=" %%A IN (cmd.config) DO SET %%A

and in my shell script, I simply use:

if [ -f "cmd.config" ]; then
    . "./cmd.config"
fi

Now, I want to add comments to the file, in shell format, like so:

# Set a custom java home with no trailing slash. Example: /home/javahome or C:\javahome
CUSTOM_JAVA_HOME=""
JAVA_FLAGS="-server -Xmx2048M"

That would work just fine in my shell script (on Linux), but breaks in my batch file (on Windows) as it tries to do a SET for that comment line.

How can I skip those lines starting with # in the FOR loop in the batch file (on Windows)?

John Cummings
  • 1,949
  • 3
  • 22
  • 38
Fede E.
  • 2,118
  • 4
  • 23
  • 39
  • 5
    use `eol=#` in `for /f` options. Thus lines starting with `#` will be igonred. – npocmaka Jul 13 '18 at 12:14
  • @npocmaka so something like this: `if exist cmd.config for /F "delims=" "eol=#" %%A IN (cmd.config) DO SET %%A` (throws me an error `"eol=#" was unexpected at this time.`). – Fede E. Jul 13 '18 at 12:24
  • You realize you are assigning two double quotes to your variables. I have programmed bash and batch scripts for many years and my best practice has always been to not assign surrounding double quotes to any variable. Just use the double quotes when using the variables with other commands to protect spaces and special characters. – Squashman Jul 13 '18 at 12:46

1 Answers1

1

As mentioned in this answer and mentioned by @npocmaka in the comments to this question, you may use eol=# to effectively ignore comments that start with # and go to the end of the line. So the call to for in your batch file would be:

if exist cmd.config for /F "eol=# delims=" %%A IN (cmd.config) DO SET %%A
John Cummings
  • 1,949
  • 3
  • 22
  • 38