Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file parameter with spaces, double quotes, pipes

I have a batch file that needs to be passed a parameter that will include pipes and spaces. Because of the spaces, double quotes need to be attached to the parameter when passing it in. I need to strip off those double quotes and echo the parameter. Normally, using the ~ would let me do this, but I think something about the specific parameters I'm passing in causes a problem. If I do this:

[test1.bat]

call test2.bat "Account|Access Level|Description"

[test2.bat]

echo %1
echo %~1

And run test1.bat, I get this output:

"Account|Access Level|Description"
'Access' is not recognized as an internal or external command, operable program or batch file.

So how do I remove the double quotes and still have a usable variable?

like image 286
SuperNES Avatar asked Mar 08 '11 22:03

SuperNES


2 Answers

You could use delayed expansion, because it doesn't care about special characters.
The only problem is to get parameter content into a variable, as it can only transfer via a percent expansion.
But in your case this should work.

@echo off
setlocal DisableDelayedExpansion
set "str=%~1"
setlocal EnableDelayedExpansion
echo !str!

Remark, I disable first the delayed expansion, so the ! and ^ aren't modified by the expansion of %1

EDIT: The delayed expansion can be disabled or enabled with

setlocal DisableDelayedExpansion
setlocal EnableDelayedExpansion

If enabled, it adds another way of extending variables (!variable! instead of %variable%), primary to prevent the parenthesis block effect of variables (described at set /?).

But the expansion with !variable! also prevents the content of any further parsing, because the delayed expansion is the last phase of batch line parsing.
In detail it is explained at how does the windows command interpreter cmd exe parse scripts

like image 194
jeb Avatar answered Nov 18 '22 18:11

jeb


@echo off
if "%~2"=="" (
    call %0 "Account|Access Level|Description" dummy
) ELSE (
    setlocal ENABLEEXTENSIONS
    for /F "tokens=*" %%A IN ("%~1") DO @echo.%%A
)

Not exactly pretty, but it works. Dealing with special characters is always a pain in batch files...

like image 34
Anders Avatar answered Nov 18 '22 20:11

Anders