简体   繁体   中英

escaping string on Windows command line

I'm trying to pass string to Win32 program from command line so it will be printed without changes.

Why I have to escape
"AAA <BBB@pobox.com>" as """AAA <BBB@pobox.com>"""
but
"AAA <BBB@pobox.com>", (comma included) as "\\"AAA ^<BBB@pobox.com^>\\","

I see no consistency in escaping rules for windows command line

PS I'm trying to generate a .cmd file

Update:

I'm using simple C program for testing that is compiled with gcc, no additional object files linked. If I replace it with perl, rules remain same.

I'm trying to create a general escaping algorithm. It will generate .cmd file which will call perl with output redirect. Currently I have a problem that if string contains odd number of double quotes which are escaped with backslash, output redirect does not function. Same problem is described in the last comment to http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx .

If I use "" as escape for ", it splits on space, so it will result it 2 parameters instead of one. Also "" has some artifacts.

In windows there is no one way of getting a command line and parsing it. Mostly programs have generally been left to deal with that themselves.

There is a recent post by Raymond Chen about the CommandLineToArgvW function which mentions various rules about quoting but they'll only apply if the program uses that particular function. http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx

In windows the command line is passed to the program unmolested (ie no wildcards expanded) and then the program needs to deal with it. The programming language may provide a convenience which does some default argument parsing, and this might use a standard windows function like CommandLineToArgvW but even so the program could opt to read the unadulterated string itself thereby skipping those standards.

This means you need to figure out the rules for the particular program you are trying to script yourself and then use them.

I've just tried those as parameters into one of my own programs, and both versions (with or without the comma) can be escaped in both ways (using either """ or \\" to escape the quotes). The only reason I can see that the < and > need to be escaped with ^ in the second version is that as the command line is seeing them as I/O redirections prior to passing them to the application, due to the different way of escaping the string quotes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM