I recently ran a command in windows cmd with single quotes in it and found that it did not behave as I expected.
From trying to google "windows batch single quote vs double quote" I've found a few articles where people asked about having windows treat single quotes like double quotes, and about how bash treats single quotes and double quotes differently. However, I couldn't easily find an explicit explanation of what single quotes do in windows batch commands.
So what do single quotes do in windows batch files? Do they perform any sort of quoting functionality at all?
Single quotes are not used at all by the cmd.exe command processor except to enclose the command to run within a FOR /F statement:
for /f %%A in ('someCommand') do ...
Or to specify a string to process by FOR /F if the USEBACKQ option is used:
for /f "usebackq" %%A in ('some string') do ...
All other quoting handled by cmd.exe is done with double quotes. However, there are Windows utilities (external commands) like WMIC that use single quotes for their own quoting purposes. But there is no standard - each utility is free to have its own interpretation of single quotes.
The inconsistent escape and quote rules used by cmd.exe vs. various command line utilities often makes it a challenge to discover the correct syntax needed for any given situation.
Here are some important notes about using double quotes "
with cmd.exe.
Double quotes are a simple state machine. The first "
turns quoting on, the next turns it off.
All special characters are treated as literal values when quoted, except for the %
and <newLine>
characters always, and the !
character if delayed expansion is enabled, and the ^
character if delayed expansion is enabled and !
also appears somewhere within the line.
If quoting is off, then you can escape a "
as ^"
to prevent it from turning quoting on. But once quoting is on, you cannot escape the closing "
. The very next "
will always turn quoting off.