Batch - How to echo exclamation mark inside string

2019-07-28 07:34发布

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

2条回答
放荡不羁爱自由
2楼-- · 2019-07-28 07:47

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
查看更多
我命由我不由天
3楼-- · 2019-07-28 07:53

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\
查看更多
登录 后发表回答