Batch argument with quotes and spaces

The batch file args.bat intended for testing:

 @echo off echo Arguments 1 to 4: echo.%~1 echo.%~2 echo.%~3 echo.%~4 

The batch file uses ~ to remove the leading quotation mark and trailing, and should display the following values ​​to the user:

 Argument 1 This is "Argument 2". 

For argument 1 it is easy:

 args.bat "Argument 1" 

However, for argument 2, everything does not work well, no matter what escape sequence I try (I found several here in Stack Overflow):

 // Didn't expect this to work, but for completeness >args.bat "Argument 1" "This is "Argument 2"." Arguments 1 to 4: Argument 1 This is "Argument 2"." 

Dropping with double quotes somehow passes double quotes to:

 >args.bat "Argument 1" "This is ""Argument 2""." Arguments 1 to 4: Argument 1 This is ""Argument 2"". 

Hiding with a stroke:

 >args.bat "Argument 1" "This is ^"Argument 2^"." Arguments 1 to 4: Argument 1 This is "Argument 2"." 

Escape with a backslash:

 >args.bat "Argument 1" "This is \"Argument 2\"." Arguments 1 to 4: Argument 1 This is \"Argument 2\"." 

Make sure I try a whole bunch of other things (ultimately, thinking about rudely forcing a solution, but asking a question first), each of which leads to a funny release, but never what I want:

 >args.bat "Argument 1" ^"This is ^^"Argument^" 2^^"." Arguments 1 to 4: Argument 1 This is "Argument" 2". 

Is it possible to pass the parameter to my batch file as I want without changing the batch file? If not, is there a way to run cmd in special mode so that it handles parameters like I want?

I have seen solutions that search for and replace double quotes, but I really want the batch file not to change.

+6
source share
1 answer

You cannot cast such an argument to %1 (or any other %<n> ).

But with a little trick it is possible.

args.bat arg1 "This! q! Argument 2! q!"

And args.bat looks like

 setlocal EnableDelayedExpansion set "q="" echo * = %* echo 1 = %~1 echo 2 = %~2 

Or is it possible

 @echo off setlocal EnableDelayedExpansion set "arg1=%~1" set "arg2=%~2" echo * = %* echo 1 = %arg1:""="% echo 2 = %arg2:""="% 

Then you can call it with args.bat "This is ""Argument 1"""

If you do not want to work with this technique, you can also analyze the arguments yourself. Then you need to take all the arguments from %* and go through each character.

Edit
If you can’t modify the scripts at all, you can use the first solution for one modification.

At the command line.

 C:\SomeDir> cmd /V:ON C:\SomeDir> set "q="" C:\SomeDir> args.bat argument1 "This is ^!q^!Argument 2^!q^!" 

Or as a single line

 cmd /v:on /c set ^^^"q=^^^"^^^" ^& test "This is ^!q^!Argument 2^!q^!" 

Using this parameter allows you to enable the delayed mode before entering the batch file; this may have some other undesirable side effects in the called batch file if it does not handle this case properly.

+3
source

Source: https://habr.com/ru/post/986934/


All Articles