Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using if condition in CMD

EDIT: I have solved my problem based on suggestions from npocmaka and magoo. Now that i understand it is indentation that caused this, can you guys please suggest how i make my code cleaner in future?

Here's my bat file:

    @echo off
    setlocal enabledelayedexpansion

    rem set lang pre-requisites
    rem Purpose can be 'test' or 'deploy'
    SET purpose="test"
    SET lang="English-India"
    SET lang_code="EnIn"

    rem if purpose is test then the folder will be EnInP101M2Tsub, if purpose is deploy then EnInP101M2DFull
    if "%purpose%"=="test"( SET folder=="%lang_code%P101M2Tsub" )
    else if "%purpose%"=="deploy"( SET folder=="%lang_code%P101M2DFull" )

    rem set required paths here
    SET audio="C:\Users\Administrator\..path..\%lang%\%purpose%\BGM\M2\%folder%\*.wav"
    SET source="C:\Users\Administrator\Downloads\Matt_Trial\..path..\%lang%\%purpose%\BGM\M2"
    SET target="C:\Users\Administrator\Downloads\Matt_Trial\..path..\%lang%\%purpose%\BGM\M3\*"

    rem copying the data
    xcopy  %source% %target% /e /i /h
    rem copying audio files into the other folders
    for /d %%a in (%target%) do copy %audio% "%%a"

    rem renaming M3 folders
    cd %target%
    for /d %%a in (*) do (
      set "p=%%a"
      set "fp=!p:~0,8!" & set "tp=!p:~10!"
      ren %%a !fp!M3!tp!
    )

** For your Understanding ** I have 2 folders in my parent folder (M1,M2,M3). Step 1: I am copying contents in M2 to a new folder M3. Step 2: I need to copy contents of a folder under M2 which has my audio into all the folders in M3. Step 3: I rename the folders under M3.

I hope I made myself clear. I have to figure out the audio path based on the set variables. I need help with the if condition part. As of now I keep getting The system cannot find the file specified. Please help!!

like image 694
Matt Avatar asked Feb 14 '26 11:02

Matt


1 Answers

A few errors.

SET will INCLUDE " after the = EXCEPT if you are using `SET "var=data" which is used to ensure that trailing spaces on the line are not included in the data assigned.

Any character after the = will be included (some need to be 'escaped' if they have a special meaning to batch, so set var==data will include the second = in the data assigned.

You haven't fallen into the spaces-in-variables trap - the syntax set var =data will set a variable named varspace not var.

There must be a space (strictly a separator, I believe) between the second operand of an IF statement and ( (if used)

Similarly, the ELSE clause must be )SpaceelseSpace( - all on the same line. This sequence of characters cannot be broken.

In your IF, you are using "%purpose%" Since purpose us set to "test" then this will be evaluated as ""test"", which is likely to be confusing, hence don't include " in your data assigned unless you have a really good reason.

like image 181
Magoo Avatar answered Feb 17 '26 05:02

Magoo