Passing a Batch File an Argument Containing a Quote Containing a Space

限于喜欢 提交于 2019-12-08 04:17:57

问题


On many occasions I have dealt with passing batch files arguments with spaces, quotes, percents, and slashes and all sorts of combinations of them. Usually I managed to figure out how to accomplish what I want, but this time I am stuck. I have tried a couple of hundred combinations now and my head is starting to hurt.

I’ve reduced the problem to a—fairly—simple requirement: pass from one batch file to another, an argument that contains some space-delimited text, one of which is a quoted space. That is, one batch file should pass some string X to another so that the the second one echos "A "B C" D". I just can’t figure out what X should be.

Here is a minimal batch file that demonstrates some attempts that do not work. (This BAT file takes the place of both by calling itself.)

::Goal is to print:
::"A "B C" D"
::ie., pass from one BAT file to another a quote containing spaces and a quote containing a space
@echo off
if not (%1)==() goto print
:passarg
  call %0 "A "B C" D"
  call %0 "A \"B C\" D"
       %0 "A ""B C"" D"
:print
  echo %1
  pause

None of those attempts work. I’ve tried using "\" \"", """ """, """" """", "\"" "\"", ""\" \""", "^" ^"", ^"" "^", and so on. Either they print double double-quotes, lose everything after the space, or something else (that is wrong).

Any ideas? Thanks.


回答1:


How about this workaround:

caller.bat:

@echo off
echo "A "B C" D">dummy.txt
call callee.bat

callee.bat:

@echo off
set /p argument=<dummy.txt
echo %argument%
pause



回答2:


This works

@echo off
if not (%1)==() goto print
:passarg
  call %0 "A "B C" D"
:print
  echo %*



回答3:


I'm new to the forum. Is quite cool, but never signed up until now.

I like the idea of calling a batch from another, very handy so you "pack" as much as possible into one single file.

I know this thread is old and hope I don't get banned or something lol

:Example.bat
@echo off

set SOMEARG=%1
set EXAMPLEARG=%2
set EXAMPLEARG=%EXAMPLEARG:""="%
set NEWFOLDER=%3
if not (%1)==() GOTO PRINT

CALL %0 SomeWord "Hey this arg has quoted "" "" spaces!" "C:\Program Files\Folder with spaces\Subfolder"

:PRINT
ECHO.
ECHO %0
ECHO %SOMEARG%
ECHO %EXAMPLEARG%
ECHO %NEWFOLDER%
ECHO.
pause

That outputs

"C:\SUT_Tools\Scripts\Testing\GLSU\Example.bat"
SomeWord
"Hey this arg has quoted " " spaces!"
"C:\Program Files\Folder with spaces\Subfolder"

Press any key to continue . . .

Hope it helps!

Sorry about my messy script, I'm not too deep into programming ;)



来源:https://stackoverflow.com/questions/2618690/passing-a-batch-file-an-argument-containing-a-quote-containing-a-space

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