goulashsoup
goulashsoup

Reputation: 3076

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

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

Upvotes: 1

Views: 848

Answers (2)

Stephan
Stephan

Reputation: 56180

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

Upvotes: 3

user6811411
user6811411

Reputation:

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\

Upvotes: 3

Related Questions