Background
I'm trying create a batch file that can copy a file to Azure Storage Explorer using azcopy. I'd like to just copy and paste my SAS key into my batch file without having to locate and escape out all the special characters (&, =, etc.) each time I do so.
My Question
How can I easily define a complex string in a batch file with those characters so that they don't get interpreted and so that I don't have to manually escape them out? Is that even possible? For example, is there some keyword or something that I can add to a set statement that basically tells it, "Hey, all the characters in this variable's value should be used as is without any interpretation"?
Some Resources I've Looked At
- https://ss64.com/nt/set.html
- https://ss64.com/nt/syntax-esc.html
- Echo exact string in windows batch file?
- https://www.tutorialspoint.com/batch_script/batch_script_variables.htm
- How do i set variables literally in batch?
In some languages you put variable values in double-quotes to make them literals. I'm not sure how to do it in a batch file.
An Example
Suppose I have this pseudo key:
nifty-11-stuff:28GOOBER:5&se=2022
Say I want to preserve and use this string EXACTLY as is in a variable, so that if I use it in my batch command later it's unchanged.
I tried this code (with quotes):
@echo off
setlocal EnableDelayedExpansion
set SAS="nifty-11-stuff:28GOOBER:5&se=2022"
echo %SAS%
pause
My Terminal output in VSCode gives this:
PS D:\git\documentationutilities> cmd /c "d:\git\documentationutilities\test.bat"
"nifty-11-stuffA28GOOBERA5&se=2022"
Notice that the :
instances are getting interpreted and thus deleted from the final value.
Thank you in advance for any help you can offer.
CodePudding user response:
The percent-signs don't even make it into the string (verify withset var
), so I used a text file with your exact string. Delayed expansion avoids the string to be parsed:
@echo off
setlocal EnableDelayedExpansion
<test.txt set /p "var="
set var
echo var=!var!
CodePudding user response:
Some time ago I build a magicEcho
macro
%magicEcho% ^%!%<> "^!%path%<>" ^
You get on the screen
^%!%<> ^ "^!%path%<>"
But for normal usage the macro is a bit of an overkill.
But perhaps you should look into the batch heredoc posts, like
heredoc for Windows batch?
or
dbenham's solution heredoc for Windows batch?
CodePudding user response:
FOR /f "delims=" %%b IN (%filename%) DO ECHO %%b
if the code can be in a file.
If you need it quoted, then echo "%%b"
If the filename contains spaces, use "usebackqdelims="
and "%filename%"