ADTC
ADTC

Reputation: 10086

Batch script (bat or cmd) - extra spaces before ampersand (or automatically escape ampersand)

Note: I understand the ^ symbol can be used to escape & symbol in batch scripts. But I need the escaping to be done automatically, as the paths are constructed at run-time. The sample script below is merely to show the problem and it is not the actual script. Please read my explanation after script output.

For some reason, commands in a batch script do not behave well with the ampersand (&) symbol in the path.

Assume you have a test.cmd or test.bat script as follows:

set TEST=A E
echo %TEST%

set TEST="A E"
echo %TEST%

set TEST=AE
echo %TEST%

set TEST="AE"
echo %TEST%

set TEST=A & E
echo %TEST%

set TEST="A & E"
echo %TEST%

set TEST=A&E
echo %TEST%

set TEST="A&E"
echo %TEST%

Here is the output:

C:\>set TEST=A E
C:\>echo A E
A E

C:\>set TEST="A E"
C:\>echo "A E"
"A E"

C:\>set TEST=AE
C:\>echo AE
AE

C:\>set TEST="AE"
C:\>echo "AE"
"AE"

C:\>set TEST=A   & E
'E' is not recognized as an internal or external command,
operable program or batch file.
C:\>echo A
A

C:\>set TEST="A & E"
C:\>echo "A & E"
"A & E"

C:\>set TEST=A  & E
'E' is not recognized as an internal or external command,
operable program or batch file.
C:\>echo A
A

C:\>set TEST="A&E"
C:\>echo "A&E"
"A&E"

Notice how the script parser adds two extra spaces before the ampersand (&) symbol when the string is not double-quoted. It also breaks up A&E into A& E before adding the two spaces, resulting in A & E

In a real-life situation, this causes problems when appending paths containing the ampersand (&) symbol in folder names to the PATH variable. Even an existing set of folder paths in PATH when referenced as set PATH=C:\Another\Folder;%PATH% gets this issue.

It occurs both in Command Prompt and in PowerShell. I have tried enableDelayedExpansion but it does not help.

Why does it behave this way? It looks like it is because & is used in Batch script to join two commands? If yes, how do I ensure it's escaped automatically (because the PATH value is automatically constructed at run-time so I cannot escape with ^ - the path is not hard-coded in the batch script).

Currently the only workaround I found (as shown above) is to enclose the whole string in double quotes ("). For the existing value of a PATH variable, I think I will need to parse the value in a loop and add quotes to every folder path in it. Is there any other (perhaps easier) workaround or permanent solution?

Upvotes: 1

Views: 1598

Answers (1)

walid toumi
walid toumi

Reputation: 2272

Enable delayed expansion and try this:

Set "test1=c:\file&folder\"
Set "test2=!test1!currentPath"
echo !test2!

For environment variables like PATH that contain & in their existing value:

set PATH=C:\Another\Folder;!PATH!

Upvotes: 4

Related Questions