Why does FOR loop command not work in a batch file which works on Windows command prompt?

前端 未结 3 1651
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 03:52
FOR /L %A IN (1,1,100) DO echo %A

The code above in a batch script results in this error:

A was unexpected at this time.

相关标签:
3条回答
  • 2020-12-04 04:40

    If you run FOR /? you'll find that the first paragraph after the parameter list starts as follows:

    To use the FOR command in a batch program, specify %%variable instead of %variable.

    As an example, let's start with a simple FOR loop:

    FOR %x in (*) DO ECHO %x
    

    This will run just fine from a command prompt, printing out the name of each file in the current directory, but if we use this verbatim in a Batch file, we'll get an error saying this:

    x was unexpected at this time.

    This is because Batch files have some extra abilities that use the percent sign immediately followed by some text, so when FOR is called from inside a Batch file it instead looks for two percent signs. So if we want to use that same FOR loop in a Batch script, we need to replace each instance of %x with %%x.

    What we end up putting in our Batch file is this:

    FOR %%x in (*) DO ECHO %%x
    
    0 讨论(0)
  • 2020-12-04 04:42

    The problem is with %, %A is for use on command lines only.

    when used in batch files %A should be substituted with %%A.

    0 讨论(0)
  • You need to use double percent characters:

    FOR /L %%A IN (1,1,100) DO echo %%A
    
    0 讨论(0)
提交回复
热议问题