问题
I have the following stript:
@ECHO OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET /A countArgs=1
...
SET /A countArgs+=1
CALL :error "!countArgs!. Argument ^-^> bla"
EXIT /B 1
...
:error
ECHO ERROR
ECHO %~1
EXIT /B 0
But the 2. ECHO
-line in the :error
routine echo
s nothing. When I reduce the CALL
argument string to "!countArgs!. Argument ^-^>"
i get a syntax error and when i reduce it to "!countArgs!. Argument ^-"
or even "!countArgs!. Argument -"
it works properly.
According to this post the character should be escaped when adding a ^
if it is inside quotes which makes sense because when using the string as a parameter in the :error
routine the ~
removes surrounded quotes...
How can i fix it?
Appreciate your help.
回答1:
there is no need to escape the >
with the call
. It's safe due to the surrounding quotes. The error occures when echoing it in the subroutine. You can use delayed expansion to echo
it:
@echo off
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET /A countArgs=1
...
SET /A countArgs+=1
CALL :error "!countArgs!. Argument -> bla"
EXIT /B 1
...
:error
ECHO ERROR
for /f "delims=" %%a in ("%~1") do echo for: %%a
echo quoted: "%~1"
set "x=%~1"
ECHO delayed: !x!
EXIT /B 0
It's safe with the call
line because of the surrounding quotes.
It's safe with the set
command, also because of the surrounding quotes.
It's safe with the echo
because of using delayed expansion (echo %x%
would fail, but echo "%x%"
would be fine - although it will show the surrounding quotes).
来源:https://stackoverflow.com/questions/50418477/batch-syntax-error-when-trying-to-echo-greater-then-sign