How to Escape Special Characters in the Command Line

Beatme CodeBY-NC-ND
3:12 read·416 words· published

Escape Special Characters in the Command Prompt

In Windows Command Prompt, you can use the escape character ^ to escape special characters.

Next, we use the command echo to inform the user of the way to view the environment variable PATH, where % needs to be written as ^% for escaping, and if it is written directly as echo %PATH%, it will result in outputting the value of the environment variable PATH.

echo Please use echo ^%PATH^% to view the environment variable PATH
Please use echo %PATH% to view the environment variable PATH

Windows Command Prompt does not support escaping with ^ in "

Note that you can’t escape with the escape character ^ in ", it will show itself.

Demonstrate the command echo again and enclose something in ' and ", respectively, to see the difference in the output.

echo Tom said, 'Please use echo ^%OS^% to view the environment variable OS'
Tom said, 'Please use echo %OS% to view the environment variable OS'
echo Tom said, "Please use echo ^%OS^% to view the environment variable OS"
Tom said, "Please use echo ^%OS^% to view the environment variable OS"

How to escape % in Windows batch files?

In the bat batch file, the escaping of % is more specific and requires the use of %% instead of ^%.

Escape Special Characters in PowerShell

In PowerShell, you can use the escape character ` to escape special characters.

Here, the command Write-Output is used to display a piece of information where `n and `t are escaped as line breaks and tabs, respectively.

Write-Output "List`n`tSalted`n`tSweet"
List
Salted
Sweet

Escape Special Characters in UNIX/Linux/macOS

In UNIX/Linux/macOS Shell programs, you can usually escape special characters using the escape character \.

The following will be escaped as a space and the Shell will jump to the folder custom lib whose name contains a space.

cd custom\ lib

Escaping in Single-Quoted Strings is not Supported

PowerShell, as well as most Shell programs in UNIX/Linux/macOS, only support escaping in double-quoted strings, or text that can be implicitly converted to a string; escaped characters in single quotes will represent themselves with no escaping effect.

By removing the two "s from the example about PowerShell, the entered text is implicitly converted to a string (which can’t contain spaces), and the output will be the same as before.

Write-Output List`n`tSalted`n`tSweet
List
Salted
Sweet

By changing " to ' in the example about PowerShell, the character ` no longer has an escape effect.

Write-Output 'List`n`tSalted`n`tSweet'
List`n`tSalted`n`tSweet