Search code examples
batch-filefor-loopcmdvariable-expansion

Variable expression %Var% not working in for loop in batch file


FOR /F "tokens=* USEBACKQ" %F IN (java -jar %MAVEN_HOME%\jenkins-cli.jar -s http://someip.com build /dev/ -s  --username **** --password ***) DO (SET var=%F)

Here %MAVEN_HOME% value is not getting replaced with the actual value but when I run this without the for loop it is working fine.

Can some please get this resolved and get the MAVEN_HOME replaced with actual value?


Solution

  • You need to put the command in ` ` like this

    FOR /F "tokens=* USEBACKQ" %F IN (`java -jar %MAVEN_HOME%\jenkins-cli.jar -s http://someip.com build /dev/ -s  --username **** --password ***`) DO (SET var=%F)
    

    because the syntax is

    C:\>for /?
    Runs a specified command for each file in a set of files.
    
    FOR %variable IN (set) DO command [command-parameters]
    
      %variable  Specifies a single letter replaceable parameter.
      (set)      Specifies a set of one or more files.  Wildcards may be used.
      command    Specifies the command to carry out for each file.
      command-parameters
                 Specifies parameters or switches for the specified command.
    
    To use the FOR command in a batch program, specify %%variable instead
    of %variable.  Variable names are case sensitive, so %i is different
    from %I.
    
    ...
    
    FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
    FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
    FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
    
        or, if usebackq option present:
    
    FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
    FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
    FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]
    

    As you can see, you have USEBACKQ so the command must be surrounded by backticks, and it also said that you have to double the percent if you want to use the for command in a batch file