Search code examples
batch-fileescapingsanitization

Batch sanitize arguments


I have the following script snippet:

if not {%2}=={} (
    if not {%3}=={} (
        "%~dp0otrtool\otrtool.exe" -x -e %2 -p %3 -D "%~dp1"" "%~f1"
    )
)

I get an error if I use a closing bracket for an input:

C:\>script.bat ).txt

The output follows:

"test"" can not be processed syntactically at this point.

C:\>        "d:\Scripts\OTRTools\otrtool\otrtool.exe" -x -e  -p  -D "C:\"" "C:\)test"

Looks like that bracket is closing one of the if-statements and I need to escape it somehow. Is there any possibility to sanitize the input appropriate?


Solution

  • The batch code with the fixes applied as suggested by SomethingDark and Aacini :

    if not "%~2" == "" (
        if not "%~3" == "" (
            "%~dp0otrtool\otrtool.exe" -x -e "%~2" -p "%~3" -D "%~dp1" "%~f1"
        )
    )
    

    It is important to use on string comparison %~2 instead of just %2 to avoid getting on execution for example if not ""second parameter"" == "" as this would be again a syntax error.

    Run call /? in a command prompt window for details on %~2 (second parameter without quotes), %~dp1 (drive and path of first parameter without quotes) and %~f1 (file name of first parameter with drive and path without quotes) and if /? for details about using conditions in batch files.