I have been trying to convert my script to allow quotes and parenthesis to be used in arguments like
script.bat -filter "Example*"
script.bat -filter "example (3.8.1)"
Quotes and parenthesis can be removed from %1 but have to be preserved in ProgramName. Can the code below to be modified accepting quotes and parenthesis?
@echo off
@setlocal enabledelayedexpansion
echo.
set "programName="
set "filterOrName="
set "listSelected=false"
:parseLoop
echo arg1: %1
IF NOT "%1"=="" (
IF "%1"=="-filter" (
set filterOrName=%1
IF NOT "%2"=="-filter" IF NOT "%2"=="-name" IF NOT "%2"=="-list" (
set ProgramName=%2
)
)
IF "%1"=="-name" (
set filterOrName=%1
IF NOT "%2"=="-filter" IF NOT "%2"=="-name" IF NOT "%2"=="-list" (
set ProgramName=%2
)
)
IF "%1"=="-list" (
set "listSelected=true"
)
SHIFT
GOTO :parseLoop
)
echo filterOrName: !filterOrName!
echo listSelected: !listSelected!
echo ProgramName: !ProgramName!
It's a common batch technic to always strip the outer quotes by using the %~1
syntax.
And everywhere where the content is used, enclose it into quotes again.
...
IF "%~1"=="-filter" ...
set "programName=%~2"
...
echo start the program
"%programName%" argument1 argument2 ...
Explanation of set "programName=%~2"
:
Here the quoted set syntax is used set "varname=content"
(the first quote HAS to be in front of the varname).
This syntax stores the content into <varname>
without quotes (only the ones if content has quotes itself).
This syntax avoids many problems, when the content contains special characters like &<>|^
.
It also avoids accidential white spaces at the end of a set var=content<space><space>
, because any content after the last quote is dropped.
Using delayed expansion
Delayed expansion solves many problems when it comes to ouput arbitrary content.
And it avoids problems, when the content contains quotes or other special characters like &|<>
Delayed expansion has the advantage, that it can expand variables without interpreting the content later.
set "var=example (3.8.1)"
echo #1 %var% - works
setlocal EnableDelayedExpansion
(
echo #2 !var! -- works
)
(
echo #3 %var% -- fails because var contains a closing parentheses
)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments