wmash
wmash

Reputation: 4202

IF statement breaks batch script

I'm writing a batch script to extract video files from their directories.
So far, it's going into the directory that matches a specific name. I am then doing a FOR loop over every item in that directory. I want to check if an item is a directory (which I have done previously), if it is then go into that directory, else do other stuff.

The problem is that the 2nd IF statement (to check whether the item is a directory or not) is breaking the batch script, giving the error:

) was unexpected at this time

If I remove that IF, the code executes as expected (I have clearly labelled which IF statement it is in the code)...

CODE:

@ECHO off

SET title=%1
SET mp4=".mp4"
SET mkv=".mkv"
SET avi=".avi"
SET minimumSize=300
SET needCompressingDir="E:\Documents\Films\Need_compressing"

CD %needCompressingDir%
FOR /f "delims=" %%i IN ('DIR /B') DO (
    IF %%i == %title% (
        IF EXIST %%i (
            CD %%i
            FOR /f "delims=" %%j IN ('DIR /B') DO (
                rem this 'IF' statement breaks it
                IF EXIST %%j (

                ) ELSE (

                )
            )
        ) ELSE (
            MOVE %%i %needCompressingDir%
        )
    )
)

Upvotes: 0

Views: 991

Answers (1)

JosefZ
JosefZ

Reputation: 30103

Read if /?:

Performs conditional processing in batch programs.

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
…
  command           Specifies the command to carry out if the condition is
                    met.  Command can be followed by ELSE command which
                    will execute the command after the ELSE keyword if the
                    specified condition is FALSE

The ELSE clause must occur on the same line as the command after the IF.  For
example:

    IF EXIST filename. (
        del filename.
    ) ELSE (
        echo filename. missing.
    )

You can see that command is mandatory part of both if and else parts. Windows cmd / .bat interpreter does not accept empty command block (): it's not considered to be a command. Use at least REM comment (a command with no effect):

        FOR /f "delims=" %%j IN ('DIR /B') DO (
            rem this 'IF' statement breaks it
            IF EXIST "%%~j\" (
              rem directory
            ) ELSE (
              rem not directory
            )
        )

Updated: use IF EXIST "%%~j\" (note trailing backslash) to check whether the item is a directory or not.

Upvotes: 3

Related Questions