02 BS Batch Programming v104
02 BS Batch Programming v104
Part I
Version
Date Author Version Changelog
● Basic
● Environment
● Flow control
● File system
● Bibliography
Basic
Basic
help and /?
● Syntax:
– HELP [command]
– [command] /?
● help set
Basic
rem, “::” and “;”
● Syntax:
– echo [{on|off}] [message]
● On/off activate/deactivate the echo
● @ prevents the echo of the command echo
– i.e. @echo blablabla.... prints “blablabla....” only
● Append a line feed
– i.e. @echo. >> manifest.mf
● Use ^ as escaping character
– i.e. echo ^> a test
Basic
getting arguments & shift
make.bat data EN
%0 %1 %2 %*
● Shift
– Changes the values of the batch parameters %0
through %9 by copying each parameter into the
previous one
:error
@echo FAILED! Errorcode: %ERRORLEVEL%
:end
Basic
error handling
– CMD1 || CMD2
● Execute CMD2 if and only if CMD1 fails
if defined %WORK_DATA_STRING_PATH% (
rmdir %WORK_DATA_STRING_PATH%\ /s /q > NUL
)
Basic
Redirection
Operator Description
Writes the command output to a file or a device, such as a
>
printer, instead of the Command Prompt window.
Reads the command input from a file, instead of reading
<
input from the keyboard.
Appends the command output to the end of a file without
>>
deleting the information that is already in the file.
Writes the output from one handle to the input of another
>&
handle.
Reads the input from one handle and writes it to the output
<&
of another handle.
Reads the output from one command and writes it to the
|
input of another command. Also known as a pipe.
Basic
Redirection
File Description
CON The console
NUL Void
LPT1 Printer on the 1st parallel port
PRN Default printer
Basic
Redirection
● Substitution:
– %VARIABLE:str1=str2%
● Substring:
– %VARIABLE:~start=noChars%
● Expression
– Character escape: ^
Operator Operation performed
<> Grouping
* / %+- Arithmetic
<< >> Logical shift
& Bitwise AND
^ Bitwise exclusive OR
| What does this ? Bitwise OR
*= /= = %= += -= &= ^= '|'= <<= >>= Assignment
, Expression separator
Environment
set
● If TEXT==ABC then...
– %TEXT:~0,1% returns A
– %TEXT:~0,2% returns AB
– %TEXT:~1,2% returns BC
– %TEXT:~-3,1% returns C
– %TEXT:~-2,1% returns B
– %TEXT:~-1,1% returns A
● Substitutes c: by d: in “PATH”
– set PATH=%PATH:c:=d:%
Environment
set
APPDATA PROCESSOR_IDENTIFIER
CD PROCESSOR_LEVEL
CMDCMDLINE PROCESSOR_REVISION
CMDEXTVERSION PROGRAMFILES
COMPUTERNAME PROMPT
COMSPEC RANDOM
DATE SYSTEMDRIVE
ERRORLEVEL SYSTEMROOT
HOMEDRIVE TEMP
HOMEPATH TMP
HOMESHARE TIME
NUMBER_OF_PROCESSORS USERDOMAIN
OS USERNAME
PATH USERPROFILE
PATHEXT WINDIR
Environment
set
C:\>set
ALLUSERSPROFILE=C:\Documents and Settings\All Users
APPDATA=C:\Documents and Settings\diego.mercado\Datos de
programa
APR_ICONV_PATH=C:\Archivos de programa\Subversion\iconv
CLIENTNAME=Console
CommonProgramFiles=C:\Archivos de programa\Archivos
comunes
COMPUTERNAME=CORWKS0170
ComSpec=C:\WINDOWS\system32\cmd.exe
DEFAULT_CA_NR=CA6
FP_NO_HOST_CHECK=NO
HOME=C:\HOME
HOMEDRIVE=C:
.......
USERDNSDOMAIN=GAMELOFT.ORG
USERDOMAIN=GAMELOFT
USERNAME=diego.mercado
USERPROFILE=C:\Documents and Settings\diego.mercado
windir=C:\WINDOWS
Environment
set
● If....
C:\>set
ALLUSERSPROFILE=C:\Documents and Settings\All Users
APPDATA=C:\Documents and Settings\diego.mercado\Datos de
programa
APR_ICONV_PATH=C:\Archivos de programa\Subversion\iconv
CLIENTNAME=Console
CommonProgramFiles=C:\Archivos de programa\Archivos
comunes
COMPUTERNAME=CORWKS0170
ComSpec=C:\WINDOWS\system32\cmd.exe
DEFAULT_CA_NR=CA6
FP_NO_HOST_CHECK=NO
HOME=C:\HOME
HOMEDRIVE=C:
.......
USERDNSDOMAIN=GAMELOFT.ORG
USERDOMAIN=GAMELOFT Means just a copy
USERNAME=diego.mercado
USERPROFILE=C:\Documents and Settings\diego.mercado
windir=C:\WINDOWS
zz=TEST
setlocal
{enableextensions | disableextensions}
{enabledelayedexpansion |disabledelayedexpansion}
@echo off
@echo off setlocal
set computername=any set computername=any
echo %computername% endlocal
echo %computername%
any CORWKS0170
Environment
setlocal & endlocal
@echo off
set VAR=before
if "%VAR%" == "before" (
set VAR=after
if "%VAR%" == "after" ( Why it doesn't work ?
@echo If you see this, it worked
)
)
Environment
setlocal & endlocal
Operator Description
EQU equal to
NEQ not equal to
LSS less than
LEQ less than or equal to
GTR greater than
GEQ greater than or equal to
Flow control
if
● Case/insensitive comparision
– IF /i “H” EQU “h” @echo succeed
– IF “h” EQU “h” @echo succeed
● Using operators
– IF %errorlevel% LSS 1 goto okay
Flow control
call
● Syntax
– call [[Drive:][Path] FileName
[BatchParameters]] [:label [arguments]]
● Do not use pipes and redirection
● i.e. call make.bat %1 %2
Flow control
call
● Used as a subroutine:
@echo off
echo 1
:sub1
echo 2 sub1
call :sub2
echo 4 What does this ?
goto end
:sub2 sub2
echo 3
goto :EOF
:end end
echo 5
flow.bat
Flow control
call
● Used as a subroutine:
@echo off
echo 1
:sub1
echo 2 sub1 C:\flow.bat
call :sub2 1
echo 4 2
goto end 3
:sub2 sub2 4
echo 3 5
goto :EOF
:end end
echo 5
flow.bat
Flow control
pushd & popd
pushd B
B
A
pushd C
C
B
A
t
Flow control
pushd & popd
popd
C
popd
B
popd
A
t
Flow control
pushd & popd
● Example:
@echo off
rem This batch file list the *.txt files in a specified
directory
pushd %1
dir
popd
cls
Flow control
pushd & popd
● Example:
@echo off
rem This batch file list the directories located at a
network direction
pushd \\Corwks5000\dfs\cor
dir
popd
Flow control
for
●
{%variable|%%variable}
– Both are case-sensitive
– %% is for scripting and % is for command-line
● (set)
– Specifies one or more files, directories, range of
values, or text strings
● command & CommandLineOptions
– The command to be executed with the current args
Flow control
for
● Basically:
– Take a set of data
– Make a FOR Parameter %%X equal to some part of
that data
– Perform a command
● optionally using the parameter as part of the command.
– Repeat for each item of data
Flow control
for
● syntax-FOR-Files
– FOR %%parameter IN (set) DO command
From command-line
c:\>FOR %%F IN (c:\windows\*.*) DO @echo %%F
From script
FOR %%F IN (c:\windows\*.*) DO @echo %%F
● syntax-FOR-Files-Rooted at Path
– FOR /R [[drive:]path] %%parameter IN (set)
DO command
From script
FOR /R %%F IN (c:\windows\*.*) DO @echo %%F
● syntax-FOR-Folders
– FOR /D %%parameter IN (folder_set) DO
command
setlocal enabledelayedexpansion
for /D %%i in (*.*) do (
cd %%i
if exist make.bat (
call make.bat %1 %2 %3 %4
if not %ERRORLEVEL%==0 (
echo ERROR:: error in %%i
What does this ? goto error
)
)
cd ..
)
:error
endlocal
Flow control
for
● syntax-FOR-List of numbers
– FOR /L %%parameter IN (start,step,end) DO
command
FOR /L %%G IN (1,1,5) DO echo %%G
1
2
3
4
5
Flow control
for
● syntax-FOR-File contents
– FOR /F ["options"] %%parameter IN
(filenameset) DO command
– FOR /F ["options"] %%parameter IN ("Text
string to process") DO command
● syntax-FOR-Command Results
– FOR /F ["options"] %%parameter IN ('command
to process') DO command
Flow control
for
Keyword Description
eol=c Specifies an end of line character (just one character).
skip=n Specifies the number of lines to skip at the beginning of the file.
Specifies a delimiter set. This replaces the default delimiter set of space and
delims=xxx tab.
each iteration. As a result, additional variable names are allocated. The m-n
form is a range, specifying the mth through the nth tokens. If the last
character in the tokens= string is an asterisk (*), an additional variable is
allocated and receives the remaining text on the line after the last token that is
tokens=x,y,m-n parsed.
Specifies that you can use quotation marks to quote file names in filenameset,
a back quoted string is executed as a command, and a single quoted string is a
usebackq literal string command.
Flow control
for
1.2.3;
version.txt
@echo off
FOR /F "eol=;tokens=1,2,3 delims=." %%i IN (version.txt) DO (
echo version1 is %%i
echo version2 is %%j
echo version3 is %%k
)
@echo on
getVersion.bat
C:\>getVersion.bat
version1 is 1
version2 is 2
version3 is 3
Flow control
for
FOR %F IN (c:\windows\*.*)
DO @echo Name:%~nxF – Size:%~zF
....
Name:ADFUUD.SYS - Size:12634
Name:AdfuUpdate.inf - Size:1562
Name:Alcmtr.exe – Size:69632
....
Flow control
for
● Syntax:
– {del|erase} [Drive:][Path] FileName [ ...]
[/p] [/f] [/s] [/q] [/a[:attributes]]
● /p: Prompts you for confirmation before deleting the
specified file.
● /f: Forces deletion of read-only files.
● /s: Deletes specified files from the current directory and all
confirmation.
● /a: Deletes files based on specified attributes.
File system
mkdir
● Syntax
– mkdir [Drive:]Path
– i.e. mkdir Work\0-preprocess\tmp creates the
3 directories
File system
rmdir / rd
● Syntax:
– {rmdir|rd} [Drive:]Path [/s] [/q]
● /s: Removes the specified directory and all subdirectories
● Syntax
– xcopy Source [Destination] [/w] [/p] [/c]
[/v] [/q] [/f] [/l] [/g] [/d[:mm-dd-yyyy]]
[/u] [/i] [/s [/e]] [/t] [/k] [/r] [/h]
[{/a|/m}] [/n] [/o] [/x]
[/exclude:file1[+[file2]][+[file3]] [{/y|/-
y}] [/z]
● /s: Copies directories and subdirectories, unless they are
empty
● /e: Copies all subdirectories, even if they are empty
overwrite
File system
xcopy
● WINDOWS XP COMMANDS
http://www.ss64.com/nt/
● LENGUAJE DE COMANDOS
http://multingles.net/docs/jmt/comandos/comandos1.html
● Gameloft wiki
https://wiki.gameloft.org/twiki/bin/view/Main/BatchScripting