- How-to: Escape Characters, Delimiters and Quotes at the Windows command line.
- Using «Double Quotes»
- Removing Quotes
- Working without Quotes
- Delimiters
- Escape Character
- Escaping CR/LF line endings.
- Escaping the pipeline
- Escaping Percents
- Escaping Exclamation marks
- Escape the Escape character
- Special Cases
- 6. Escape Characters
- Books and eBooks
- Contact
- You can buy the content of this Shell Scripting Tutorial as a PDF!
- How-to: Escape characters, Delimiters and Quotes
- Special characters
- Command Separator
- Quotation Marks
- Verbatim arguments —%
- Concatenating Strings
- Backslash \
- Here strings
- Delimiters
How-to: Escape Characters, Delimiters and Quotes at the Windows command line.
Using «Double Quotes»
If a single parameter contains spaces, you can still pass it as one item by surrounding in «quotes» — this works well for long filenames.
If a parameter is used to supply a filename like this:
This parameters will be:
To launch a batch script with spaces in the Program Path requiring «quotes»
In the FIND comand, the » quote can be escaped by doubling it to «»
Removing Quotes
Several methods for removing quotes are listed on the dequote page.
Working without Quotes
Without surrounding quotes, a long filename will be passed as %1 %2 %3.
To refer to the pathname above use %* rather than %1 %2 %3 — the %* will cover all parameters — even if there are more than %9
You can apply Extended Filename syntax to %* with the following workaround:
Delimiters
Delimiters separate one parameter from the next — they split the command line up into words.
Parameters are most often separated by spaces, but any of the following are also valid delimiters:
Comma (,)
Semicolon (;)
Equals (=)
Space ( )
Tab ( )
If you are passing a parameter to a batch file that contains any of these delimiter characters, it will split the parameter into two parameters unless you surround the whole thing with double quotes: «this is;one=param,»
Notice that although / and — are commonly used to separate command options, they are absent from the list above. This is because batch file parameters are passed to CMD.exe which can accept it’s own parameters (which are invoked using / and — )
One exception to this standard list of delimiters is the FOR command where the default is just [space] and [tab] and you can use the delims= option to specify something different.
When using the TAB character as a delimiter be aware that many text editors will insert a TAB as a series of SPACEs.
When you use %* to refer to all parameters, the value returned will include the delimiters, under NT 4.0 this will include the leading space, under Windows 2000 and above it won’t.
Escape Character
Adding the escape character before a command symbol allows it to be treated as ordinary text.
When piping or redirecting any of these characters you should prefix with the escape character: & \ ^ |
Escaping CR/LF line endings.
The ^ escape character can be used to make long commands more readable by splitting them into multiple lines and escaping the Carriage Return + Line Feed (CR/LF) at the end of a line:
Mark Yocom [MSFT] has more on this technique here.
A couple of things to be aware of:
- A stray space at the end of a line (after the ^) will break the command, this can be hard to spot unless you have a text editor that displays spaces and tab characters.
- If you want comment something out with REM, then EVERY line needs to be prefixed with REM.
Alternatively if you use a double colon :: as a REM comment, that will still parse the caret at the end of a line, so in the example above changing the first line to :: ROBOCOPY… will comment out the whole multi-line command.
Some commands (e.g. REG and FINDSTR) use the standard escape character of \ (as used by C, Python, SQL, bash and many other languages.)
The \ escape can cause problems with quoted directory paths that contain a trailing backslash because the closing quote » at the end of the line will be escaped \» .
To save a directory path with a trailing backslash ( \ ) requires adding a second backslash to ‘escape the escape’
so for example instead of «C:\My Docs\» use «C:\My Docs\\»
To be sure that a path includes a trailing backslash, you can test for it:
Set _prog=C:\Program Files\SS64 App
IF %_prog:
Escaping the pipeline
When a pipe is used, the expressions are parsed twice. First when the expression before the pipe is executed and a second time when the expression after the pipe is executed. So to escape any characters in the second expression double escaping is needed:
The line below will echo a single `&` character:
Escaping Percents
The % character has a special meaning for command line parameters and FOR parameters.
To treat a percent as a regular character, double it:
Many characters such as \ = ( ) do not need to be escaped when they are used within a «quoted string» typically these are characters you might find in a filename/path. The percent character is one exception to this rule, even though under NTFS % is a valid filename character.
Escaping Exclamation marks
When the shell is running in EnableDelayedExpansion mode the ! character is used to denote a variable and so must be escaped (twice) if you wish to treat it as a regular character:
Escape the Escape character
The escape character can be used to escape itself ^^ (meaning don’t treat the first ^ as an escape character), so you are escaping the escape character:
Special Cases
A small number of commands follow slightly different rules, FINDSTR, REG and RUNAS all use \ as an escape character instead of ^
“All the best stories in the world are but one story in reality — the story of escape. It is the only thing which interests us all and at all times, how to escape”
6. Escape Characters
Certain characters are significant to the shell; we have seen, for example, that the use of double quotes («) characters affect how spaces and TAB characters are treated, for example:
So how do we display: Hello «World» ?
The first and last » characters wrap the whole lot into one parameter passed to echo so that the spacing between the two words is kept as is. But the code:
would be interpreted as three parameters:
So the output would be
Note that we lose the quotes entirely. This is because the first and second quotes mark off the Hello and following spaces; the second argument is an unquoted «World» and the third argument is the empty string; «».
Thanks to Patrick for pointing out that this: is actually only one parameter (no spaces between the quoted parameters), and that you can test this by replacing the echo command with (for example) ls .
Most characters ( * , ‘ , etc) are not interpreted (ie, they are taken literally) by means of placing them in double quotes («»). They are taken as is and passed on to the command being called. An example using the asterisk (*) goes:
In the first example, * is expanded to mean all files in the current directory.
In the second example, *txt means all files ending in txt .
In the third, we put the * in double quotes, and it is interpreted literally.
In the fourth example, the same applies, but we have appended txt to the string.
However, » , $ , ` , and \ are still interpreted by the shell, even when they’re in double quotes.
The backslash (\) character is used to mark these special characters so that they are not interpreted by the shell, but passed on to the command being run (for example, echo ).
So to output the string: (Assuming that the value of $X is 5):
we would have to write:
We have seen why the » is special for preserving spacing. Dollar ( $ ) is special because it marks a variable, so $X is replaced by the shell with the contents of the variable X . Backslash ( \ ) is special because it is itself used to mark other characters off; we need the following options for a complete shell:
So backslash itself must be escaped to show that it is to be taken literally. The other special character, the backtick, is discussed later in Chapter 12, External Programs.
Books and eBooks
My Shell Scripting books, available in Paperback and eBook formats.
Buy this tutorial as a PDF for only $5 $1!
Shell Scripting Tutorial is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and to keep by your desk as an ever-present companion. | Shell Scripting: Expert Recipes for Linux, Bash and more is my 564-page book on Shell Scripting. The first half explains the features of the shell; the second half has real-world shell scripts, organised by topic, with detailed discussion of each script. |
Contact
You can mail me with this form. If you expect a reply, please ensure that the address you specify is valid. Don’t forget to include the simple addition question at the end of the form, to prove that you are a real person!
You can buy the content of this Shell Scripting Tutorial as a PDF!
How-to: Escape characters, Delimiters and Quotes
The PowerShell escape character is the grave-accent( ` )
The escape character can be used in three ways:
1) When used at the end of a line, it is a continuation character — so the command will continue on the next line.
2) To indicate that the next character following should be passed without substitution. For example $myVariable will normally be expanded to display the variables contents but `$myVariable will just be passed as $myVariable
3) When used inside double quotation marks, the escape character indicates that the following character should be interpreted as a ‘special’ character.
Special characters
Special characters are used to format/position string output.
The `r (carriage return) is ignored in PowerShell (ISE) Integrated Scripting Environment host application console, it does work in a PowerShell console session.
Using the Escape character to avoid special meaning.
When setting a string variable the # character does not need to be escaped, but at the command line # will act as a comment unless escaped:
PS C:\> echo 1 # 1
1
PS C:\> echo 1 `# 1
1
#
1
The escaped quotes allow quotation marks to be displayed on screen rather than being interpreted as the start or end of a string. The same effect can also be achieved by doubling-up the quote marks: «» or »
For powershell.exe, the horizontal tab stops are every 8th character.
Command Separator
A semicolon ; can be used to split up multiple commands on the same line.
First-command ; Second-command ; Third-command
which is equivalent to:
First-command
Second-command
Third-command
The semicolon Command Separator can be thought of as a short code for a Carriage Return/Newline. It is equivalent to & in the CMD Shell.
To have the second command run only if the first fails: Try
Quotation Marks
Either single or double quotes may be used to specify a literal string.
Single-Quoted Strings ( ‘ )
When you enclose a string in single quotation marks, any variable names in the string such as ‘$myVar’ will appear exacly as typed when the command is processed. Expressions in single-quoted strings are not evaluated, not even escape characters or any of the Special characters listed above. If the string contains any embedded single quotes, they must be doubled (replace ‘ with » )
$msg = ‘Every «lecture» should cost $5000’
While single quotes do not evaluate expressions or variables, they do evaluate wildcards, so the following two expressions both evaluate to True:
Double-Quoted Strings ( » )
When you enclose a string in double quotation marks, any variable names in the string such as «$myVar» will be replaced with the variable’s value when the command is processed. You can prevent this substitution by prefixing the $ with an escape character. Any embedded double quotes can be escaped `» or doubled (replace » with «» )
If you nest a Single-Quoted String inside a larger Double-Quoted string, the double-quoted rules apply. Similarly if you nest a Double-Quoted String inside a larger Single-Quoted string, the single-quoted rules apply. The outermost quotes always determine the behaviour.
«Every «»cake»» should cost `$5″
«Every ‘cake’ should cost `$5»
$var = 45
«The value of » + ‘$var’ + «is ‘$var'»
«The value of `$var is ‘$var'»
$query = «SELECT * FROM Customers WHERE Name LIKE ‘%JONES%'»
Verbatim arguments —%
In PowerShell 3.0 the special Stop Parsing symbol —% is a signal to PowerShell to stop interpreting any remaining characters on the line. This can be used to call a non-PowerShell utility and pass along some quoted parameters exactly as is.
for example instead of escaping every character that PowerShell may interpret:
PS C:\> FIND.EXE ‘»Search Text»‘ «C:\Program Files `(x86`)\Demo\text.txt »
we can instead use:
PS C:\> FIND.EXE —% «Search Text» «C:\Program Files (x86)\Demo\text.txt »
Any PowerShell variables after the —% won’t be expanded but you can work around this by building up the command string using more than one variable:
$command = ‘FIND.EXE —%’
$params = «C:\Program Files (x86)\Demo\text.txt»
If the command type is Application, the parameter —% is not passed to the command. The arguments after —% have any environment variables (strings surrounded by %) automatically expanded. For example:
PS C:\> FINDSTR.EXE —% «%ProgramFiles%»
In the above %ProgramFiles% is replaced with the value $env:ProgramFiles
Concatenating Strings
Concatenate strings with +
In many cases, when combining simple strings, the + operator is not needed:
PS C:\> $first = «abcde»
PS C:\> $second = «FGHIJ»
PS C:\> «$first $second»
abcde FGHIJ
but when combining more complex objects, the + operator becomes very useful:
For example if we retrieve an environment variable
$drive = gci env:SystemDrive
This returns a DictionaryEntry object with .name and .value properties.
# Adding this to a string will give the wrong result
PS C:\> «aaa $drive bbb»
aaa System.Collections.DictionaryEntry bbb
# Concatenating it with a string is closer, but still wrong:
PS C:\> «aaa » + $drive + » bbb»
aaa System.Collections.DictionaryEntry bbb
# Specify the .value property and concatenate that with + to get the desired result:
PS C:\> «aaa » + $drive.value + » bbb»
aaa C: bbb
# Alternatively use the $( ) SubExpression operator:
PS C:\> «aaa $($drive.value) bbb»
aaa C: bbb
(an easier method would be using $drive = $env:SystemDrive which will return a system.string in the first place.)
Backslash \
In many programming languages including C# (.Net) and most UNIX shells the escape character is \
PowerShell is a Windows shell, and Windows already uses the backslash as a path separator C:\Windows\… .
In Windows CMD the escape character is ^ although this was not a great choice as ^ is a valid character in NTFS filenames.
The PowerShell designers could have adopted the forward slash as a path separator C:/Windows/… , and then allocated the backslash as the escape character but this would have caused huge confusion and so instead they left paths unchanged and allocated ` as the escape character.
The backtick ` is a valid character in NTFS filenames, so should you encounter one in a filename, it will need to be escaped.
In some PowerShell expressions (matching operations) a backslash character will be interpreted as the start of a Regular Expression, (e.g. \w = match word) this is the industry-standard regex syntax.
To escape this and treat the backslash as an ordinary character, double it (replace \ with \\ )
PowerShell currently uses CommandLineToArgvW to process command line inputs, Raymond Chen has some examples.
Here strings
A here string is a single-quoted or double-quoted string which can span multiple lines.
Variables and Expressions in single-quoted strings are not evaluated.
All the lines in a here-string are interpreted as strings, even though they are not enclosed in quotation marks.
$myHereString = @’
some text with «quotes» and variable names $printthis
some plain text
and the children’s toys
‘@
If the above were a single quoted string, the ‘ in children’s would need to be escaped.
If it was a double quoted string, you’d need to escape the instances of » and you’d need to escape the $ if you didn’t want variable expansion.
$anotherHereString = @»
The value of `$var is $var
some more text
«@
Inside a here-string, double and single quotes are not special but quoted literally, all line breaks are preserved.
The @ character is also used to create arrays, create hash tables and as a splat operator.
Delimiters
Delimiters separate one parameter from the next — they split the command line up into words.
The standard delimiter for PowerShell is the space character, in addition the split operator and import-csv both accept options for splitting strings with a choice of delimiter.
“Be not angry that you cannot make others as you wish them to be, since you cannot make yourself as you wish to be” — Thomas A Kempis