iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🤖

Handling Special Characters in cmd.exe

に公開

Windows Command Interpreter

I tried to write regular expressions on the Windows command line, but the results were the opposite of what I expected and things didn't work well.
While I eventually realized the cause was that symbols weren't being escaped correctly, I didn't know how to escape them properly in cmd.exe, so I summarized my findings through trial and error.
Verified on Windows Server 2019.

Summary

  • Escape some symbols for each command being executed.
  • When using a pipe (|) with internal commands, multi-escape the caret (^).
  • When using delayed expansion of environment variables, escape the caret (^) even inside double quotes (").
Symbol DOS-compatible command Batch file C/C++ runtime Remarks
Space " " *1 " " *1 " " Separator
! ^^! ^^^^^^^^^^! "^!" Delayed expansion env var
" ^" ^" "\"" Toggle switch to disable special chars
% *2 *2 *2 Environment variable
& ^& ^^^& ^& "&" Multiple commands
' *3 *3 *3
( - - - Multiple commands
) - - - Multiple commands
+ *3 *3 *3
, "," *1 "," *1 *3 Separator
; ";" *1 ";" *1 *3 Separator
< ^< ^^^< ^< "<" Redirection
= "=" *1 "=" *1 *3 Separator
> ^> ^^^> ^> ">" Redirection
@ - - - Hiding command
[ *3 *3 *3
\ - - \ "\" "\\" *4 Path separator
] *3 *3 *3
^ ^^ ^^^^ *5 ^^^^ ^^^^^^^^ *5 ^^ "^" "^^" *5 Escape
` *3 *3 *3
{ *3 *3 *3
| ^| ^^^| ^| "|" Pipe
} *3 *3 *3
~ *3 *3 *3

*1: Possible by enclosing parameters if the command supports removing ".
*2: If no environment variable matches, it can be left as is. See below for cases where a match is possible.
*3: The manual states that file and directory names require quotes, but it works without them.
*4: Escaping is required only when preceding \".
*5: Additional escaping is required when delayed expansion environment variables are specified.

Command Line Evaluation

There are several stages from the time a Windows program is launched from the command line until it receives parameters:

  1. String substitution via environment variables
  2. Escaping symbols
  3. Separation of multiple commands
  4. Preparation for redirection
  5. Delayed expansion of environment variables
  6. Extraction of %0 from the command line
  7. Launching programs and the command interpreter
  8. Parameterization by the runtime

String substitution via environment variables

If there are two or more percent signs (%) on the command line, the string within the first and second ones is extracted, and if it matches an environment variable name, string substitution is performed.
Differences between uppercase and lowercase in environment variable names are ignored.
Even if the value of the expanded environment variable contains a string with %, it will not be expanded recursively.
If it doesn't match an environment variable, the original string is left as is.
If expansion is successful, the process repeats with the third and fourth percent signs; if no match was found, it tries the second and third, and so on.

Only in the case of batch files, %0 to %9 and %* are expanded as arguments. This occurs before environment variable expansion. %% is expanded to a single %, and any % that doesn't fall into any category is deleted.

It is not possible to escape % as a character outside of batch files. You can prevent matching an environment variable name by inserting an escape character that will be deleted later, like %PATH^%, or by creating and incorporating an environment variable containing the desired value.

Escaping symbols

The caret (^) is an escape character. Instead of being literal, the ^ is removed and the character immediately following it is treated as a normal character, even if it is a special character. If it is at the end of a line, the command line can be continued.
If there is a string enclosed in double quotes ("), the special characters included are treated as normal characters. Since escape characters are also disabled inside double quotes, you cannot include a double quote within them.
However, environment variable expansion via % takes place first and cannot be suppressed.
Even if double quotes are not closed, it is not an error. In that case, everything until the end of the command line remains valid.

Separation of multiple commands

The symbols &, |, &&, ||, and ( ) remaining after escaping are interpreted as delimiters for multiple commands.
Also, the at sign (@) has the same effect as enclosing the section from that point until the next closing parenthesis ) or the end of the command line in ( ). This is originally a syntax for disabling echo-back in batch files.
The order of precedence is ( ) > @ > | > & > && > ||.

Preparation for redirection

Whitespace characters, =, ;, ,, and any < or > remaining after escaping are interpreted as command line delimiters.
When the command line is divided into multiple blocks by inserting breaks immediately before delimiters, blocks starting with redirection (<, >) are collectively removed from the command line passed to the program.
Also, if a block immediately preceding < or > is a single digit (0 through 9), that digit is also removed as part of the redirection.
Double quotes (") specified in filenames during redirection are removed.

Delayed expansion of environment variables

If delayed expansion of environment variables is enabled and there are two or more exclamation marks (!) on the command line, they are expanded with environment variables similarly to %.
For some reason, if delayed expansion is enabled, ^ is removed at this point even if there is at least one !. This cannot be prevented even if enclosed in ".

Batch files behave differently when there is no match with the command line. The process of extracting the string between the first and second signs is the same, but if there is no match, the string including both ! is deleted and it proceeds to the string between the third and fourth. Any ! that is not escaped and does not match anything is deleted.

! can be escaped by prefixing it with ^. However, since it is evaluated twice, it must be specified as ^^. Also, it can be escaped by creating and incorporating an environment variable containing the desired value and using delayed expansion.

Extracting %0 from the command line

Whitespace characters, =, ;, and , continue to be interpreted as command line delimiters.
The specification for the command to be executed is what is extracted from the first block, up to just before a / or the end of the block.

Only when specifying an internal command, additional logic applies, and even if the following character is +, ., :, /, \, <, >, [, or ], it will be accepted as a command.

Launching programs and the command interpreter

The program is launched from here.
If one of the command pipelines connected by a pipe (|) includes an internal command or multiple commands, it is handed over to another command interpreter for execution.
C:\Windows\system32\cmd.exe /S /D /c" command"
Since environment variable expansion and escape character processing are also executed in the destination command interpreter, you must understand the number of calls and apply multiple levels of escaping to get the correct result.

An interesting phenomenon occurs if @ follows immediately after |. Everything after @ is treated as a single unit, and commands connected by &—which normally wouldn't be part of the pipeline—are passed to the command interpreter all at once. Since symbols are expanded again in the new command interpreter, extensive multi-escaping may be required.

Parameterization by the runtime

The command line is passed as an unquoted string, and it is the responsibility of each program to split it into parameters.
Internal commands ECHO and TITLE process the string including all whitespace following the command.
(However, it seems ECHO voluntarily removes the leading symbol.)
Batch file parameters are split using whitespace, =, ;, and ,. Note that within a batch file, evaluation equivalent to the command line is performed line by line, so escape characters in parameters referenced by %1, etc., are consumed even at this point.
Programs using the C/C++ runtime are split using whitespace. They treat the part enclosed in " as a single parameter after removing the surrounding quotes, and implement features such as treating \" as " if it exists inside.

Escaping double quotes

Most symbols are just a matter of adding ^ or enclosing them in " if you pay attention to the number of escape levels. The most troublesome part is likely the escaping when you want to specify a literal " for a program using the C/C++ runtime.

The C/C++ runtime defines \" as an escape sequence to represent a double quote within a quoted string. The command interpreter does not understand this intent and treats \" as a toggle switch to disable/enable special characters. This creates a discrepancy where the C/C++ runtime sees it as inside the quotes while the command interpreter sees it as outside.

For example, if the parameter you want to get is \^, you can write it as "\^". However, to change it to \"^, you must write it as "\\\"^^". Just trying to insert a single character causes widespread rewrites across the string.

Adding escapes

The rules for rewriting are:

  1. Escape " to \".
  2. Escape any consecutive \ immediately preceding \" to \\.
  3. Escape symbols between one \" and the next with ^.

Since it is unrealistic for a human to manage these states, you can use a sed script to apply the escape characters. From a parameter "\\\"^" containing \", you get "\\\"^^^".

For Bash
sed -e 's/"\([^"]*\)"/\tA\1\tB/g;s/^/\tB/;:a;s/\(\tB[^\t]*\)\([&|<>%^"]\)/\1\tC\2/g;ta;s/^\tB//;s/\tC/^/g;s/\t./\"/g'
For Cmd
sed -e "s/\"\([^^\"]*\)\"/\tA\1\tB/g;s/^^/\tB/;:a;s/\(\tB[^^\t]*\)\([^&^|^<^>^%^^\"]\)/\1\tC\2/g;ta;s/^\tB//;s/\tC/^/g;s/\t./\\\"/g^"

This method has a drawback: if the command interpreter's double quote remains open at the end, the behavior of subsequent parameters or commands will also be affected.

Disabling double quotes

This method involves effectively disabling the special character toggle switch provided by ". All special characters are prefixed with ^ instead. The above example can be written as ^"\\\^"^^^".

Delayed evaluation of environment variables

Since the delayed expansion of environment variables is executed after symbol escaping, inserting a " through expansion does not affect the toggle switch. You can escape it by creating an environment variable, incorporating it, and then using delayed expansion. Note that delayed expansion using ! is disabled by default.

SET ^^D=\"

Considering that ^ inside double quotes is also removed when delayed expansion is active, the aforementioned parameter can be written as "\\!^D!^^".

Afterword

The reason I got the opposite result of what I expected was that the escape was applied to the [^0-9] following \", resulting in [0-9].

References

Cmd | Microsoft Docs
Using command redirection operators | Microsoft Docs
Windows CMD Command Syntax - SS64.com

Discussion