Zero logo

Batch Files

A batch file is a text file with a .bat file extension. It contains a series of commands to be executed by the command line interpreter. You can run a batch file from a command prompt by navigating to its containing folder and typing its name, or just double-click on the file. Unless stated otherwise, examples on this page are run by double-clicking on the file name, which automatically opens a command prompt and runs the script.

Background

Reason for writing this section is to provide enough information for writing batch scripts to run the various command line utilities found in Uniform Server. After reading this section, you will be able to understand how some of the included batch scripts work.

Note: Directory and folder are interchangeable. Directory comes from the early days of DOS programming.

Basic batch file template

Uniform Server is portable and does not change the host environment. For portability, each batch file must be located in the root folder UniServerZ or a folder below this. Ideally, each file should be autonomous, meaning it can be run by another batch file or application. The following template meets this requirement.

In folder UniServerZ, create a new file named test1.bat with the following content:

test1.bat

@echo off
rem ### working directory current folder 
pushd %~dp0

echo This is test script 1
echo.

rem ### restore original working directory
popd

pause
  Comments

A) Batch file command "@echo off" prevents displaying of command lines.

B) Batch file command "rem" allows you to add comments to document the script.

C) The batch file command pair "pushd %~dp0" and "popd", apart from saving and resorting a caller's location, forces current working directory to the location of the file containing the command pair.

D) Command "echo" outputs the string that follows to the screen.
The special command "echo." outputs a blank line. Note: there is no space between echo and the full stop.

E) The command "pause" halts execution, allowing you to read the screen. This command is generally used for test purposes; without it, the screen (command prompt) closes.

Test
Run the batch file by double-clicking on file test1.bat:

  • A command window opens.
  • The string "This is test script 1" without the quotes is displayed.
  • The message "Press any key to continue . . ." is the result of the pause command.
  • Pressing any key closes the window.

Folder hierarchy – Moving around

Knowing where you are in the folder hierarchy is extremely important. The current working directory is provided by %CD%, a top-level environment variable. A copy is passed to the command prompt. Value contained in this variable is that of the calling application. Our template forces this to the location of our script. Within our batch file, we can use the command "CD" to change this environment variable. It is unfortunate the command and environment variable have identical names "CD". However, the command "CD" means change directory and environment variable %CD% means current working directory.

In folder UniServerZ, create a new file named test2.bat with the following content:

test2.bat
@echo off
rem ### working directory current folder 
pushd %~dp0

rem #------Test code -----------
set HOME=%CD%
echo A) Command used was HOME=%%CD%%
echo Environment variable HOME is %HOME%
echo The current working directory is %CD%
echo.
pause

CD www
echo B) Command used was CD www
echo Environment variable HOME is %HOME%
echo The current working directory is %CD%
echo.
pause

CD ..\..\
echo C) Command used was ..\..\
echo Environment variable HOME is %HOME%
echo The current working directory is %CD%
echo.
pause

CD %HOME%\core\apache2
echo D) Command used was CD %%HOME%%\core\apache2
echo Environment variable HOME is %HOME%
echo The current working directory is %CD%
echo.
pause

rem #------ End test code ------

rem ### restore original working directory
popd
  Comments

The "set" command is used for creating environment variables. The environment variable name is assigned a value; this value can be another environment variable. To use environment variables, you must enclose their name between %'s; for example, %var_name%. Note: to echo a %, use %%.

A) The line "set HOME=%CD%" creates a new environment variable HOME and sets it to the current working directory using environment variable %CD%.
Line "echo Command used was HOME=%%CD%%" prints the text "Command used was HOME=%CD%"
Next two lines print the variables %HOME% and %CD%. Note: the paths displayed are identical.

B) Command "CD www" changes the working directory to folder www

C) Command "CD ..\..\" means move up two folder levels. Changes the working directory to this new folder.

D) Command "CD %HOME%\core\apache2" changes the working directory to folder apache2. The path is constructed using the HOME environment variable and appending folders to create the full path to apache2.

Notes:

Generally, there is no need to change the working directory. However, there are applications that specifically require you to set the working directory to their binary folder or otherwise, they will not run. After running this type of application, the HOME variable allows you to return to your scripts home folder.

Test
Run the batch file by double-clicking on file test2.bat:

  • Each test is displayed and paused.
  • Check the full paths displayed correspond to expected results.

Folders and Files – Create, delete and redirection operator

This section covers basic commands "md" (make directory), "rd" (remove directory), "mov" (move file), "copy" (copy file), "ren" (rename files), "del" (delete file), direction operator ">" to create a file and direction operator ">>" for appending to a file.

In folder UniServerZ, create a new file named test3.bat with the following content:

test3.bat
@echo off
rem ### working directory current folder 
pushd %~dp0

rem #------Test code -----------
set HOME=%CD%

echo A) Creating folders
IF NOT EXIST aaa md aaa
IF NOT EXIST bbb\ccc md bbb\ccc
echo Check folders created
pause
echo. 

echo B) Creating files in folder aaa
echo. > aaa\z_test1.txt
echo Line 1 > aaa\z_test2.txt
echo Line 2 >> aaa\z_test2.txt
echo Check files created
pause
echo. 

echo C) Moving, copying and renaming files
move aaa\z_test1.txt bbb\ccc\z_test1.txt 
copy aaa\z_test2.txt bbb\ccc\z_test2.txt >nul
ren  aaa\z_test2.txt z_test3.txt
echo Check files moved, copied and renamed
pause
echo. 

echo D) Deleting folders
rd   aaa
rd   bbb\ccc
echo Fails because folders not empty
pause
echo. 

echo E) Empty folders and delete
del aaa\z_test3.txt
del bbb\ccc\z_test1.txt
del bbb\ccc\z_test2.txt
rd   aaa
rd   bbb\ccc
rd   bbb
echo Folders aaa and bbb deleted
pause
echo. 

rem #------ End test code ------

rem ### restore original working directory
popd
  Comments

A) The command IF NOT EXIST checks if the named folder does not already exist before attempting to create it. If the folder does not exist, it is created using command "md" (make directory).

B) The "echo" command and redirection operator ">" write text to the named file. The named file is either created if it does not exist or overwritten if it already exists. The redirection operators ">>" append text to an existing file. The special command "echo." (no space between echo and the full stop) allows an empty file to be created (a file with no content).

C) Command "move" moves a file to a different location, "copy" copies a file to a specified location and "ren" renames an existing file.

  • move source_path_file_name destination_path_file_name
  • copy source_path_file_name destination_path_file_name
  • ren path_file_name new_name

Note: Commands "move" and "copy" output confirmation text. You can discard the output using the command ">nul".

D) E) The command "rd" (remove directory) deletes the named folder. Before a folder can be deleted, it must be empty. Delete any files and folders in may contain.

Test
Run the batch file by double-clicking on file test3.bat:

  • Follow instructions displayed.
  • Check results at each step against the script.

IF and IF ELSE command

Perform conditional processing in batch programs.

The basic "IF" command syntax is shown below.

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command

If (condition) (command1)
If (condition) (command1) Else (command2) 

The "IF" command can use compound commands statements; a single command is replaced with several commands, separated by the "&" character as follows:

If (condition) (command1 & command2)
If (condition) (command1 & command2 ) Else (command3 & command4 )

The "&" operator is required only if you write the code on one line, as shown. However, the "&" operator is not required when the code is written in a block. The following two examples demonstrate this.

A) "IF" written on single line:

IF EXIST z_test4.txt (echo File exist; deleting & DEL z_test4.txt) ELSE (echo File doesn't exist; creating file & echo Line 1 > z_test4.txt)

B) "IF" written as a block:

IF EXIST z_test4.txt (
  echo File exist; deleting
  DEL z_test4.txt
) ELSE (
  echo File doesn't exist; creating file
  echo Line 1 > z_test4.txt
)

Set /p command - user and file input

The SET command displays, sets, or removes environment variables. Changes made with SET will remain only for the duration of the current script session.

In folder UniServerZ, create a new file named test4.bat with the following content:

test4.bat
@echo off
rem ### working directory current folder 
pushd %~dp0

rem #------Test code -----------
set HOME=%CD%

echo A) Setting password file path
set PWD_FILE1=%HOME%\htpasswd\mysql\passwd.txt
set PWD_FILE2=%HOME%\htpasswd\mysql\passwd.txt
set PWD_FILE2=
echo Password file %%PWD_FILE1%% is %PWD_FILE1%
echo Password file %%PWD_FILE2%% removed ..%PWD_FILE2%..
pause
echo.

echo B) Prompt for user input
Set /P UserInput=Please enter yes or no  || Set UserInput=NoInput
If "%UserInput%"=="NoInput" Exit
If /i "%UserInput%"=="no" Exit
If /i "%UserInput%"=="yes" echo OK next test
pause
echo.

echo C) Getting MySQL password from file
set /p MYSQL_PWD=<%PWD_FILE1%
echo MySQL Password = %MYSQL_PWD%
echo.
pause

echo D) Alternative get MySQL password from file
FOR /F %%G IN (%PWD_FILE1%) DO set MYSQL_PWD2=%%G
echo MySQL Password = %MYSQL_PWD2%
echo.
pause

rem #------ End test code ------

rem ### restore original working directory
popd
  Comments

A) Set/Delete variable:
The command format "set some_variable = some_value" sets the environment variable to a new value string or to an existing environment variable name. The command format "set some_variable =" removes (deletes) the variable.

B) Prompt for user input:
The "/P" switch allows you to set a variable equal to a line of input entered by the user. The prompt string is displayed before the user input is read. Note: the prompt string can be empty.
If a user just presses Enter, the variable will be unchanged and an errorlevel will be set.

The test code can be changed as follows; it uses the "goto" command to execute different code.

Set /P UserInput=Please enter yes or no  || Set UserInput=NoInput
If "%UserInput%"=="NoInput" goto sub_1
If /i "%UserInput%"=="no" goto sub_2
If /i "%UserInput%"=="yes" goto sub_3

C) Set from text file:
The redirection operator "<" reads the first line of a specified text file and puts it into the environment variable. It uses the following command format:

Set /P Some_Var=<Path_Some_text_file_name.txt

D) Alternative Set from text file:
The content of a file can be read using the FOR /F command as shown below:

FOR /F %%G IN (%PWD_FILE1%) DO set MYSQL_PWD2=%%G

The content of file PWD_FILE1 is read into memory and processed. The first line is assigned to variable "%%G". This variable is used to set the variable "MYSQL_PWD2", which completes the command.

Test
Run the batch file by double-clicking on file test4.bat:

  • Follow instructions displayed.
  • Check results at each step against the script.

Summary

The above has introduced you to the main commands used in batch files. At the least, you now know what to search for on the Internet.

There is one command (FOR /F) that is extremely useful and is worth expanding in details. This is covered on Batch Files- Passing parameters page. It allows you to easily pass parameters between batch files and applications run from a batch file.


--oOo--