| # 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: The 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:
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 callers 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. |  | 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
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 displayed "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 a top-level environment variable %CD% 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 commend "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:
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 prints 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 ..\..\" Relative paths can be used ..\..\ 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 otherwise they will 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. |  | 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 varailbe HOME is %HOME%
    echo The current working directory is %CD%
    echo.
    pause

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

    CD ..\..\
    echo C) Command used was ..\..\
    echo Environment varailbe 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 varailbe HOME is %HOME%
    echo The current working directory is %CD%
    echo.
    pause

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

    rem ### restore original working directory
    popd

    pause
## 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 deleted file, direction operator > to create a file and the direction operator >> for appending to a file. In folder UniServerZ create a new file named test3.bat with the following content:
Comments A) The command IF NOT EXIST checks the named folder does not exist before attempting to create it. If the folder does not exist it is create using command md (make directory) B) The echo command and redirection operator > writes text to the named file. The named file is either created if it does not exist or overwrites an existing file. The redirection operators >> append text to an existing file. The special command echo. (note no space between echo and the full stop) allows an empty file to be create (a file with not content). C) Command move moves a file to 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. This text can be suppressed by redirecting output to the null folder using the redirection operator >>null. 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. |  | 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 >null
    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

    pause
## 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 seperated 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 show. 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 z_test4.txt exist deleting & DEL z_test4.txt) ELSE (echo file does not exist creating file & echo Line 1 > z_test4.txt)
B) "IF" written as a block:
    IF EXIST z_test4.txt (
      echo File z_test4.txt exist deleting
      DEL z_test4.txt
    ) ELSE (
      echo file does not 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:
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 return the variable will be unchanged and a 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=NothingEntered
    If "%UserInput%"=="NothingEntered" 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 into memory and processed. The first line is assigned to variable %%G. This variable is used to set the variable MYSQL_PWD2 which comletes 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. |  | 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=NothingEntered
    If "%UserInput%"=="NothingEntered" 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
## 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 page . it allows you to easily pass parameters between batch files and applications run from a batch file. --oOo--