Bash in Git for Windows: Weirdness when running a command with CMD.exe /C with args

前端 未结 7 2241
后悔当初
后悔当初 2020-12-05 02:55

This is more of an annoyance rather than a problem but I would very much like to understand the semantics here.

All I want to do is to run an arbitrary command on a

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 03:12

    As I explain here, there is an additional alternative when using modern Git for Windows' bash

    MSYS_NO_PATHCONV=1 cmd /c echo test
    

    Explanation of each attempt

    TL;DR

    The unfortunate answer is in Windows, there are many ways arguments can be parsed, and you have to format your output in bash in such a way that is will be reparsed by the windows program it the way it expects

    Second, third, and forth attempts are all actually identical

    This is the same as (in cmd) > cmd "/c echo test". Windows cmd only uses " quotes, so somewhere between the runtimes, your (in bash) $ cmd '/c echo test' converts all the arguments to "/c echo test" which is happily parses.

    Since from a bash point of view, the 2nd/3rd/4th attempt are all the same, they all give the same response. The surprise " is due to how windows parsing only using " and not ', hence it is the same as > cmd "/c echo test"

    Fifth attempt

    $ cmd "/c echo" test is the same as > cmd /c echo" test. (I'm guessing: The space after the /c is optional, so cmd isn't confused by /c echo being the space being literal due to the first quote.) So it is trying to execute the command echo" test which doesn't exist. The space is interpreted as literal because of the quote. Likewise, if you had done $ cmd "/c echo "test you would get the output "test, because the space is no longer being treats as literal, and no longer part of the command echo

    Note: > cmd "/c echo" test and > cmd /c echo" test error the same. My guess here is that cmd parsed everything after the /c on its own, so the initial " has no affect, as parsing starts all over again. Chalk that up to special cmd weirdness.


    This can actually be reproduced using python for windows, which has nothing to do with msys/mingw/git/bash/glibc/etc...

    python -c "import subprocess; subprocess.Popen(['cmd', '/c echo test'])"
    

提交回复
热议问题