Batch - syntax error when trying to echo greater-then sign (>)

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-06 06:05:35

问题


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 echos 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!