James H.
James H.

Reputation: 5

Escape from ampersand in batch variables

I'm trying to put together a complex batch script that does multiple things at once. I'm getting hung on one portion of it. I want the script to ask for a customer number then place that number in a specific spot in a URL. The problem is that the URL has an ampersand and when I echo the variable contents it gives an error.

@echo off
set /p id="Enter ID: "
set URL=https://firsturlsectionhere.com
set FULLURL=%URL%id%^&therestofurl
@echo %FULLURL%

Any help you guys could give would be great.

Upvotes: 0

Views: 1530

Answers (1)

Squashman
Squashman

Reputation: 14320

If you set your variable with quotes then you do not need to escape the ampersand. But because you have the ampersand you need to echo the variable with delayed expansion.

 @echo off
 set /p id="Enter ID: "
 set URL=https://firsturlsectionhere.com
 set "FULLURL=%URL%/%id%&therestofurl"
 setlocal enabledelayedexpansion
 echo !FULLURL!
 endlocal
 pause

If you keep the escape character in the variable and quote surround your set command then you can echo the variable as is.

 @echo off
 set /p id="Enter ID: "
 set URL=https://firsturlsectionhere.com
 set "FULLURL=%URL%/%id%^&therestofurl"
 echo %FULLURL%
 pause

Upvotes: 1

Related Questions