1

I'm trying compress folders using batch script with 7zip

But SET function inside if statement is not working ;(

Folders structure:

2000/
   01/
   02/
   03/
   04/
   05/
   06/
   07/
   08/
   09/
   10/
   11/
   12/
2001/
   01/
   02/
   03/
   04/
   05/
   06/
   07/
   ...

Here is my code:

@ECHO OFF
setlocal
echo %date%
set logMonth=%date:~4,2%
set logDay=%date:~7,2%
set logYear=%date:~10,4%
set path="C:\Program Files\7-Zip\";%path%

if %logMonth% EQU 01 (

set logMonth=12
set /a logYear=%logYear%-1
7z a -tzip c:\%logYear%%logMonth%.zip   C:\files\v2-output\%logYear%\%logMonth%

) ELSE (

rem 1 saraas busad sar bol tuhain onii umnuh sariin folderiig ziplene 
set /a logMonth=%logMonth%-1
7z a -tzip c:\%logYear%%logMonth%.zip   C:\files\v2-output\%logYear%\%logMonth%

)
endlocal

If current month equivalent 01 compress folder last month of previous year, else compress previous month of current year. Help guys!

1 Answer 1

2

Within a block statement (a parenthesised series of statements), the ENTIRE block is parsed and THEN executed. Any %var% within the block will be replaced by that variable's value AT THE TIME THE BLOCK IS PARSED - before the block is executed.

Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.

Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the chnaged value of var or 2) to call a subroutine to perform further processing using the changed values.

Note that any calculation performed by a set /a assumes that any string starting 0 is an OCTAL constant, hence set /a var+=%month% will produce an error for month=08 (August) or 09 (September) because 8 and 9 are not valid OCTAL characters.

Set /a suppresses leading zeroes, so set /a var=03 will set var to 3, not 03. Classically, to calculate using a DECIMAL value with a leading zero, you'd use set /a value=1%value% - 1 and then use [or set value to] %value:~1%

So - try

if %logMonth% EQU 01 (
 set /a logMonth=112
 set /a logYear=%logYear%-1
) ELSE (
 rem 1 saraas busad sar bol tuhain onii umnuh sariin folderiig ziplene 
 set /a logMonth=1%logMonth%-1
)
set logmonth=%logmonth:~1%
7z a -tzip c:\%logYear%%logMonth%.zip   C:\files\v2-output\%logYear%\%logMonth%
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.