lee
lee

Reputation: 87

The ^ gets doubled when sending string as parameter to function in batch script

This is my code:

set var1="`netsh int ipv4 show interface ^| findstr /I Network`"

call:GetEles %var1%
goto:eof

:GetEles
for /F "tokens=1 usebackq" %%F IN (%~1) do echo %%F
goto:eof

When I check the command while it is running, the ^ becomes doubled inside function :GetEles:

for /F "token=1 usebackq" %%F IN (`netsh int ipv4 show interface ^^| findstr /I Network`) do echo %%F

That doubled ^ makes my script failing, how can I solve it?

Upvotes: 4

Views: 205

Answers (3)

Compo
Compo

Reputation: 38579

Try it like this, (the call will not expand the %var1% to a point which will expose the poison character).

set "var1='netsh int ipv4 show interface ^| findstr /I Network'"

call:GetEles "%%var1%%"
goto:eof

:GetEles
for /F %%F IN (%~1) do echo %%F
goto:eof

You will note that tokens=1 wasn't needed and neither was usebackq

Upvotes: 2

aschipfl
aschipfl

Reputation: 34899

As others already described, this is a nasty "feature" of the call command.

There are several options to work around that:

  1. Simply undo the caret doubling in the sub-routine:

    @echo off
    set "VAR=caret^symbol"
    call :SUB "%VAR%"
    exit /B
    
    :SUB
        set "ARG=%~1"
        echo Argument: "%ARG:^^=^%"
        exit /B
    
  2. call introduces a second parsing phase, so let the second one expand the variable:

    @echo off
    set "VAR=caret^symbol"
    call :SUB "%%VAR%%"
    exit /B
    
    :SUB
        echo Argument: "%~1"
        exit /B
    
  3. Pass the value by reference (so the variable name) rather than by value:

    @echo off
    set "VAR=caret^symbol"
    call :SUB VAR
    exit /B
    
    :SUB
        setlocal EnableDelayedExpansion
        echo Argument: "!%~1!"
        endlocal
        exit /B
    
  4. Do not pass the variable value to the sub-routine, read the (global) variable there instead:

    @echo off
    set "VAR=caret^symbol"
    call :SUB
    exit /B
    
    :SUB
        echo Argument: "%VAR%"
        exit /B
    

Upvotes: 4

JosefZ
JosefZ

Reputation: 30103

Read Buggy behaviour when using CALL:

Redirection with & | <> does not work as expected.

If the CALL command contains a caret character within a quoted string "test^ing", the carets will be doubled.

Try following code snippet:

@echo off
SETLOCAL EnableExtensions

set "var1=`netsh int ipv4 show interface ^| findstr /I "Network"`"

call:GetEles "%var1%"
goto:eof

:GetEles
echo variable  "%var1%"
echo parameter "%~1"
for /F "tokens=1 usebackq" %%F IN (%var1%) do echo %%F
goto:eof

Output:

d:\bat> D:\bat\SO\41769803.bat

variable  "`netsh int ipv4 show interface ^| findstr /I "Network"`"
parameter "`netsh int ipv4 show interface ^^| findstr /I "Network"`"

Upvotes: 3

Related Questions