Search code examples
batch-file

Backslash causes errors on variables


If I try setting a variable that has a backslash it causes an error.

if %errorlevel% equ 3 set crntPath=%crntPath%!directories[%%n]!

I simply want to add Acer\ to C:\Users\Program Files (x86)\ yet this gives me an error saying:

\!directories[%n]! was unexpected at this time.

I do not understand why it does this, I can add Acer\ to C:\Users\Program Files\, but not C:\Users\Program Files (x86)\.

Here is the full source code:

@echo off
setlocal enabledelayedexpansion
set crntPath=C:\Program Files (x86)\
set dontrepeat=0
:getFiles
for /l %%n in (1,1,250) do (
    set "files[%%n]="
    set "directories[%%n]="
)
set pointing=1
set /a count=1
for /f "delims=" %%i in ('dir "%crntPath%" /B /AD') do (
    set directories[!count!]=%%i
    set /a count+=1
)
set oldcount=%count%
for /f "delims=" %%i in ('dir "%crntPath%" /B /A-D') do (
    set files[!count!]=%%i
    set /a count+=1
)
set directories[0]=..
goto main
:outputFiles
cls
set dontrepeat=1
echo %crntPath%
for /l %%n in (0,1,%count%) do (
    if "!directories[%%n]!" neq "" (
        if %pointing% equ %%n (
            if %pointing% equ 0 (
                if %errorlevel% equ 3 for %%D in ("%crntPath:~0,-1%") do set crntPath=%%~dpD&goto getFiles
            ) else (
                if %errorlevel% equ 3 set crntPath=%crntPath%!directories[%%n]!
                rem error???
            )
            echo [DIR] !directories[%%n]!
        ) else (
            echo !directories[%%n]!
        )
    )
)
for /l %%n in (%oldcount%,1,%count%) do (
    if "!files[%%n]!" neq "" (
        if %pointing% equ %%n (
            if %errorlevel% equ 3 "%crntPath%!files[%%n]!"
            echo [FILE] !files[%%n]!
        ) else (
            echo !files[%%n]!
        )
    )
)
goto main

:main
if %dontrepeat% equ 0 goto outputFiles
choice /c zxc /n
if %errorlevel% equ 1 set /a pointing-=1 & if !pointing! lss 0 (set /a pointing=%count%-1)
if %errorlevel% equ 2 set /a pointing+=1 & if !pointing! geq %count% (set /a pointing=0)
set dontrepeat=0
goto outputFiles

I've tried switching all backslashes to forward slashes yet it still doesnt work.


Solution

  • It happens because of the parentheses in your variable value. But the problem could theoretically be any special symbol that is offensive to a batch script. Better to declare with double quotes:-

    set crntPath="C:\Program Files (x86)\"
    

    Of course, you'll have to modify your script to accomodate this particular change. (For eg. dir %crntPath% /b /a-d )

    If you want to add append something to it, you could do :-

    for /f "tokens=*" %%i in (%crntPath%) do set crntPath="%%~i!directories[%%n]!"
    

    Using double-quotes is generally advisable for all paths especially if storing them in variables.