Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping ampersands in Windows batch files

I realise that you can escape ampersands in batch files using the hat character

e.g.

echo a ^& b
a & b

But I'm using the command

for /f "tokens=*" %%A IN ('DIR /B /A-D /S .acl') DO ProcessACL.cmd "%%A"

which is finding all the files named '.acl' in the current directory, or a subdirectory of the current directory.

The problem is, I'm finding path names that include the '&' character (and no, they can't be renamed), and I need a way of automatically escaping the ampersands and calling the second batch file with the escaped path as the parameter.

rem ProcessACL.cmd
echo %1
like image 570
Bryan Avatar asked Nov 03 '10 13:11

Bryan


People also ask

How do I escape a space in a batch file?

Three Ways to Escape Spaces on WindowsBy enclosing the path (or parts of it) in double quotation marks ( ” ). By adding a caret character ( ^ ) before each space. (This only works in Command Prompt/CMD, and it doesn't seem to work with every command.) By adding a grave accent character ( ` ) before each space.

What is Exit B in batch file?

/b. Exits the current batch script instead of exiting Cmd.exe. If executed from outside a batch script, exits Cmd.exe. <exitcode> Specifies a numeric number.

How do I stop a batch file from exiting?

Add a pause statement to a batch file If you're creating a batch file and want the MS-DOS window to remain open, add PAUSE to the end of your batch file. This prompts the user to Press any key. Until the user presses any key, the window remains open instead of closing automatically.

What does %% mean in batch file?

Represents a replaceable parameter. Use a single percent sign ( % ) to carry out the for command at the command prompt. Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> )


1 Answers

The problem is not the escaping, it seems to be in the second script.

If there is a line like

echo %1

Then it is expands and fails:

echo You & me.acl

Better to use delayed expansion like

setlocal EnableDelayedExpansion
set "var=%~1"
echo !var!

To avoid also problems with exclamation points ! in the parameter, the first set should be used in a DisabledDelayedExpansion context.

set "var=%~1"
setlocal EnableDelayedExpansion
echo !var!
like image 193
jeb Avatar answered Sep 22 '22 03:09

jeb