Batch - How to echo exclamation mark inside string passed as parameter to subroutine?

有些话、适合烂在心里 提交于 2019-12-11 07:45:40

问题


I have the following script:

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

SET /A countArgs=1

FOR %%p in (%pathListToCheck%) DO (
    IF NOT EXIST %%p (
        CALL :error "!countArgs!. Argument -> bla!"
        EXIT /B 1
    )
    SET /A countArgs+=1
)

:error
    ECHO ERROR  
    set x=%~1
    ECHO !x!
EXIT /B 0

Unfortunately the exclamation mark does not get echod. I also tried to escape it like ^! and ^^! but it doesn't work.

I use delayed expension here to make the greater-then sign (>) work. If i would try to ECHO the parameter directly (ECHO %~1) it would fail. For details see my previous question

How can fix this?

I appreciate your help...


回答1:


You didn't read/understand Stephans summary in his answer.
setlocal enabledelayedexpansion is the cause of the vanished exclamation marks.
There is no reason to use it in your present code.

If you want to echo <|>& without qoutes you have to escape those. That can be done by code.

:: Q:\Test\2018\05\19\SO_50419709.cmd
@Echo off
SetLocal EnableExtensions DisableDelayedExpansion

SET /A countArgs=1

set "pathlisttocheck=%userprofile%,x:\x\x\"
FOR %%p in (%pathListToCheck%) DO (
    IF NOT EXIST %%p (
        CALL :error "%%countArgs%%. Argument -> bla!  %%~p"
        EXIT /B 1
    )
    SET /A countArgs+=1
)
EXIT /B 1

:error
ECHO ERROR  
set "x=%~1"
set "x=%x:>=^>%"
ECHO %x%
EXIT /B 0

Sample output:

> Q:\Test\2018\05\19\SO_50419709.cmd
ERROR
2. Argument -> bla! x:\x\x\



回答2:


If you escape the exclamation mark and disable delayed expansion inside the function, it works (although it removes the "delayed" alternative - which you didn't like anyway)

@echo off
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET /A countArgs=2
CALL :error "!countArgs!. Argument -> bla^!"
EXIT /B 1

:error
  setlocal disabledelayedexpansion
    for /f "delims=" %%a in ("%~1") do echo for:      %%a
    echo quoted:  "%~1"
  endlocal
EXIT /B 0


来源:https://stackoverflow.com/questions/50419709/batch-how-to-echo-exclamation-mark-inside-string-passed-as-parameter-to-subrou

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