batch-file

Batch file if condition to check file type failing under specific conditions


I have been at this for a few days and can't figure out why this is not working.

I had made this to run with lf file manager but I'm testing it from command prompt with file.bat test.mkv or file.bat testfolder

So this works (goto blocks excluded for brevity, but it has the same issue without using goto):

set attr=%~a1%

if %attr:~0,1% == d (
    goto :runexplorer
) else (
    goto :subl
)

But this with additional if else's doesn't:

set attr=%~a1%

if %attr:~0,1% == d (
    goto :runexplorer
) else if %~x1% == .mkv (
    goto :runffplay
) else if %~x1% == .opus (
    goto :runffplay
) else (
    goto :subl
)

I get this error when I pass a folder as the argument but works for files:

set attr=d-a--------
( was unexpected at this time.

On Windows11 if that helps.

Thanks.


Solution

  • Here's a quick example of how I'd suggest the code you posted should be done.

    If Exist "%~1\." GoTo runexplorer
    If /I Not "%~x1" == ".mkv" (
        If /I Not "%~x1" == ".opus" (
            GoTo subl
        )
    )
    
    :runffplay
    

    If you really have more extensions for the :subl label then the following structure may work better for you:

    If Exist "%~1\." GoTo runexplorer
    For %%G In (mkv opus) Do (
        If /I "%~x1" == ".%%G" (
            GoTo runffplay
        )
    )
    
    :subl