How to pass redirection characters (<and>) to a function of a Windows batch file?
Assume this batch file
call :SomeFunction "a string with an > arrow" goto:eof :SomeFunction echo %~1 goto:eof Result of this
call: SomeFunction "a string with an> arrow" echo a string with an 1> arrow goto: eof goto: eof
and a file called arrow is created that contains a string with an . Pay attention to 1> .
How can I prevent the shell from interpreting > as a redirection character in this situation? (Hint: I tried ^> and it is not.)
EDIT: Of course, other operators ( | and & ) also influence.
To do this, you can use the FOR /F command, and not:
echo %~1 Use this:
FOR /F "delims=" %%i IN ("%~1") DO echo %%i Edit: note that now you need to deal with strange escaping behaviors when passing an argument separated by double quotes. For example, "a^2" will be escaped as "a^^2" , it does not matter if you try using "a^^2" or "a\^2" . What you can do (according to your own comment) is to use a temporary variable and do the escaping (then remove the double quotes):
set TEMP=%TEMP:>=^>% If you don't want to worry about escaping, you can also try:
set "tmp="many \ ^ > ' characters and quotes"" Pay attention to double quotes to enclose the set argument and many special characters in the string. In this case, the tmp environment variable will be literally: "many \ ^ > ' characters and quotes" , you can simply use it as:
FOR /F "delims=" %%1 IN (%tmp%) DO echo %%1 Note %1 instead of "%~1" . Let's complicate the situation now. If you need a double quote " , then some characters will not be escaped (for example, & and | ). You can simply remove the quote:
set "tmp=many \ ^ > ' | & characters and quotes" B:
FOR /F "delims=" %%1 IN ("%tmp%") DO echo %%1 or
FOR /F "delims== tokens=2" %%1 IN ('set tmp') DO echo %%1 Remember that you can use hints to delimit the FOR line if you specify the usebackq option. You can use a temporary file or ... better ... PowerShell script ...
As the name says foxidrive, CALL modifies the carriage, so itβs not possible to create a bulletproof way to pass parameters by value via CALL.
But instead, you can use the options by reference.
@echo off set "var=a string with a caret^ and an > arrow" call :SomeFunc var exit /b :SomeFunc setlocal EnableDelayedExpansion set "param1=!%1!" echo !param1! exit /b I am using a delayed extension here, as this is the best way to safely handle any variable contents.