BAT file tips

Let's play with BAT files a little. As you may know, BAT files are intended to be run and processed by the MS command processor, named cmd.exe, and the programming language they are created with is very close to BASIC. The early versions of the BAT-files language (which comes from famous Windows ancestor, MS-DOS) were very limited. Nowadays it has more features and a few days ago I created a small collection of interesting tricks, related to BAT file programming. You can check the following examples that demonstrate which execution flow controlling statements BAT-file language has and show their analogs in PHP.

Simple IF statement that checks whether the VAR variable contains 1 and, if so, prints the message "VAR is 1":

BAT-file: PHP:
SET VAR=1
IF "1" == "%VAR%" ECHO VAR is 1
$var = 1;
if (1 == $var) echo 'VAR is 1';

Executing more then one command in IF true statement:

BAT-file: PHP:
IF EXIST MYFILE.TXT (
	DEL MYFILE.TXT
	ECHO File is deleted
) ELSE (
	ECHO File does not exist
)
if (file_exist('MYFILE.TXT')) {
	unlink('MYFILE.TXT');
	echo 'File is deleted';
} else {
	echo 'File does not exist';
}

Using switch-like construction instead of series of IF statements:

BAT-file: PHP:
GOTO CASE_%I%
:CASE_0
	ECHO i equals 0
	GOTO END_SWITCH
:CASE_1
	ECHO i equals 1
	GOTO END_SWITCH
:END_SWITCH
switch ($i) {
case 0:
	echo "i equals 0";
	break;
case 1:
	echo "i equals 1";
	break;
}

Defining and calling a procedure:

BAT-file: PHP:
CALL :UNPACK_FILE MY_FILE.ZIP

REM The GOTO :EOF separates the main 
REM program and procedures.
GOTO :EOF

REM Procedure UNPACK_FILE
REM @param string %1
:UNPACK_FILE
	7z.exe x %1
GOTO :EOF
unpackFile('MY_FILE.ZIP');



/**
 * unpackFile function
 * @param string $file
 */
function unpackFile($file) {
	exec("7z.exe x $file");
}

Calling a procedure by the name:

BAT-file: PHP:
SET PROCEDURE=UNPACK_FILE_7Z
CALL :%PROCEDURE% MY_FILE.ZIP
$procedure = 'unpackFile7z';
$procedure('MY_FILE.ZIP');

Modify variable by its name:

BAT-file: PHP:
SET VARIABLE=VAR1
SET %VARIABLE%=TEST
ECHO %VAR1%
$variable = 'var1';
$$variable = 'TEST'
echo $var1;

Save command result into variable (actually, it saves into the variable only the first line of the command result):

BAT-file: PHP:
DIR > RESULT.TXT
SET /P DIR_RESULT=< RESULT.TXT
DEL RESULT.TXT
exec('DIR', $output);
$dirResult = $output[0];

String Replace

BAT-file: PHP:
SET MSG=Hello username!
SET MSG=%MSG:username=Tom%
ECHO %MSG%
$msg = 'Hello username!';
$msg = str_replace('username', 'Tom', $msg);
echo $msg;

String Spit

BAT-file: PHP:
SET DATE=2007-08-23

CALL :SPLIT_DATE %DATE:-= %
ECHO YEAR: %YEAR%
ECHO MONTH: %MONTH%
ECHO DAY: %DAY%
GOTO :EOF

:SPLIT_DATE
SET YEAR=%1
SET MONTH=%2
SET DAY=%3
GOTO :EOF
$date = '2007-08-23';

list($year, $month, $day) = implode('-', $date);

echo 'Year :' . $year;
echo 'Month: ' . $month;
echo 'Day: ' . $day;

See also about BAT files and Windows Shell: