batch-file – Best Practices – Quotes

Most online batch scripts come with a lot of quote issues.

Examples and Solutions

Example A

if %var%==abc echo Test

This code works – when the content of %var% does not contains space or other special characters. Now let’s assume %var% contains 1 whitespace. Now cmd.exe sees:

if  ==abc echo Test

This would cause a failure because cmd.exe doesn’t understand this syntax.

Solution A

if "%var%"=="abc" echo Test

Using quotes, cmd.exe sees the entire %var%(including space and special characters) as only one normal string. Yet this is not the safest comparison method. The safest one uses echo, pipe, and findstr.

Example B

cd C:\User\Spaced Name\Spaced FileName.txt

cd would only change directory to C:\User\Spaced, as cd only accepts one path argument.

Solution B

Simply by adding quotes around the path, the issue would be solved.

cd "C:\User\Spaced Name\Spaced FileName.txt"

There are also a few examples that work better using quotes, like the set /a statement, etc. But, when one works on strings that contain spaces or special characters, it is usually much safe to use quotes.

if you want to reproduce, please indicate the source:
batch-file – Best Practices – Quotes - CodeDay