简体   繁体   中英

How to escape special characters on batch file when setting variable

I need to set a variable with the string !5[4U}~YfWWre"4a inside a batch script. I'm aware that I have to escape some special characters there but I couldn't quite get it right.

My delayed variable expansion is ON, and based on https://www.robvanderwoude.com/escapechars.php , I tried this:

  • SET PASS=^^!5[4U}~YfWWre"4a
  • SET PASS=^^!5[4U}~YfWWre"4a
  • SET PASS=^^!5[4U}~YfWWre""4a
  • SET "PASS=!5[4U}~YfWWre"4a"
  • SET "PASS=^^!5[4U}~YfWWre"4a"
  • SET "PASS=^^!5[4U}~YfWWre""4a"

None of them have worked for me. What am I doing wrong?

@ECHO OFF
SETLOCAL

SET "var=!5[4U}~YfWWre"4a"
ECHO var=%var%
SET var
GOTO :EOF

works perfectly well for me... but you're using delayedexpansion so

@ECHO OFF
SETLOCAL enabledelayedexpansion

SET "var=^!5[4U}~YfWWre"4a"
ECHO var=%var%
SET var
GOTO :EOF

which shows that it depends on quite how you are displaying the string.

@ECHO OFF
SETLOCAL enabledelayedexpansion
SETLOCAL disabledelayedexpansion
SET "var=!5[4U}~YfWWre"4a"
ECHO var=%var%
SET var
endlocal&SET "var=%var:!=^!%"
ECHO var=%var%
SET var

GOTO :EOF

demonstrates the same phenomenon - and if the string contains multiple ! like !5[4U}~!YfWWre"4a the difference between echo which evaluates the string and set which does not is even greater.

so the quick answer would be - go back to disabledelayedexpansion mode when using the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM