Is this a bug in windows batch?

南笙酒味 提交于 2020-01-16 00:56:11

问题


I have found a peculiar issue with batch scripting that I cannot seem to explain. Maybe its just because I do not know enough about the underpinnings of how batch works but here is an example batch file (test.bat):

@echo off

FOR /F "tokens=1*" %%i in ("%*") DO (
    echo %%j
)

if I call it like so:

test.bat ab a,b "a,b"

I get this as my output:

a,b "a b"

Why was the second comma stripped out? If I escape the comma like so:

test.bat ab a,b "a^,b"

I get the correct output:

a,b "a,b"

It is almost like ',' is considered a delimiter by the for loop, but when I look at FOR /?, the only default delim is white space. Comma is not listed as a delim. If I specifically state that the delim is a space, I still get this behavior. If I escape the quotes, I still get this behavior. Anyways, if comma was a delim, the first comma should also be stripped out right?. Oddly enough if you try to use 'usebackq' with the for loop, you get the exact opposite. The first comma is stripped out and the second one is preserved:

a b "a,b"

Why do I have to escape all commas inside quotes for this to work? Is there some whindows rule I am missing or is it just a bug in windows batch scripting?


回答1:


  1. Comma is a separator in command line Reading second argument in batch file if first argument has commas
  2. When you call FOR /F "tokens=1*" %%i in ("%*") , when expanding, it becomes

    FOR /F "tokens=1*" %%i in ("ab a,b "a,b"") Now you see you have double quotes opening and closing 2 times. Hope this helps.

  3. My advice, if yo need sophisticated command line parameters parsing use
:loop
 rem you code here
 shift
goto :loop

There're some limitations when using for with %*.




回答2:


@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "line=a b a,b "a,b""
SET line
ECHO [%*]
FOR /f "tokens=1*" %%i IN ("%*") DO (ECHO %%j)
FOR /f "tokens=1*" %%i IN ("%line%") DO (ECHO %%j)
FOR /f "tokens=1*" %%i IN ("!line!") DO (ECHO %%j)
FOR /f "tokens=1*" %%i IN ('echo %line%') DO (ECHO %%j)

GOTO :EOF

Running the above may point to an explanation. It's all a matter of history - quite when a substitution is made - %var% first, %%x second and !var! third.



来源:https://stackoverflow.com/questions/20617065/is-this-a-bug-in-windows-batch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!