问题
I'm trying to execute a command with git-bash using cmd. I need to pass the command for it to execute. The problem is I need to pass the path of the batch file into the command and it has spaces. I can't seem to be able to pass quotes to "cmd" in a way that it will understand it.
cmd //C "c:\Program Files (x86)\another path\file.bat args && echo done"
That will give me an error:
'C:\Program' is not recognized as an internal or external command, operable program or batch file.
If I try using single quotes then it passes a literal backslash to cmd.
cmd //C '"c:\Program Files (x86)\another path\file.bat" args && echo done'
Which will give me the error the same error but show the backslashes:
'\"c:\Program Files (x86)\another path\file.bat\"' is not recognized as an internal or external command, operable program or batch file.
回答1:
For CMD /C, see "Bash in Git for Windows: Weirdness when running a command with CMD.exe /C with args"
Try using a Unix-style path, within double-quotes
$ CMD //C "/c/Program Files (x86)/Opera/New folder/a.bat"
(no && echo done
)
Tested with git version 2.11.0.windows.1 on Windows 10.
Note: For simple commands, you don't need a CMD /C
to execute a bat from a git bash session. In that case, you can escape spaces and parenthesis:
vonc@vonc MINGW64 /c/Users/vonc
$ /c/Program\ Files\ \(x86\)/Test/New\ folder/a.bat
The OP adds in the comments:
I want the environment variables to only exist on the one instance of
cmd
. I don't want it to actually set the environment variables in bash.
Which is why the "&&
" is necessary, as the other command would rely on those variables. That's the only command I need to rely on them for.cmd /C "C:/path to/vcvarsall.bat && echo %LIB%"
should print the env variable set by the batch file.
Then in git-bash I wantecho $LIB
to print nothing after executing the command.
echo %LIB%
is tricky because the CMD session would use the echo from Git, instead of the echo
builtin CMD shell command.
But chaining multiple command in a CMD (adapted here for a Git bash session) is done with:
cmd //V //C "C:/path to/vcvarsall.bat&&set myvar"
set myvar
will display the value set for myvar
by the bat script.
And yet, back in the bash session, an echo ${myvar}
would not display anything.
回答2:
And another simple way is to navigate to the directory(using cd command) that contains that file and then run the command and pass the filename.
来源:https://stackoverflow.com/questions/41917804/executing-command-with-cmd-that-contains-spaces-through-git-bash