Batch File Read File Contents Into Variable

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 tin can run a batch file from a command prompt past navigating to its containing folder and typing its proper noun or just double click on the file. Unless stated otherwise examples on this page are run past double clicking on the file name which automatically opens a command prompt and runs the script.

Groundwork

Reason for writing this department is to provide enough data for writing batch scripts to run the various control line utilities constitute in Uniform Server. Afterwards reading this section you lot will exist able to sympathize how some of the included batch scripts work.

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

Basic batch file template

Compatible Server is portable and does not modify the host surround. For portability each batch file must be located in the root binder UniServerZ or a folder below this. Ideally each file should be autonomous significant it can be run by some other batch file or awarding. The following template meets this requirement.

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

Comments

A) Batch file control "@repeat 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 electric 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 control "repeat." outputs a blank line. Note in that location is no space between repeat and the total stop

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

test1.bat
                    @echo off rem ### working directory current folder  pushd %~dp0  repeat This is test script 1 repeat.  rem ### restore original working directory popd  suspension                

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

  • A control window opens.
  • The string "This is test script i" without the quotes is displayed.
  • The message displayed "Press any primal to go along . . ." is the consequence of the pause command.
  • Pressing any central closes the window.

Folder hierarchy – Moving around

Knowing where yous are in the binder hierarchy is extremely important. The current working directory is provided past 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 employ the command "CD" to alter this environment variable. It is unfortunate the control and environment variable take identical names "CD" however, the commend "CD" means change directory and environment variable %CD% ways electric current working directory.

In binder UniServerZ create a new file named test2.bat with the post-obit content:

Comments

The set command is used for creating environs variables. The environment variable proper name is assigned a value, this value tin be another surround variable. To use environment variables you must enclose their proper noun betwixt %'s for example %var_name%. Note to repeat a % employ %%.

A) The line set HOME=%CD% creates a new environment variable Home and sets it to the current working directory using surround variable %CD%.
Line "echo Command used was Domicile=%%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 world wide web

C) Command "CD ..\..\" Relative paths can be used ..\..\ means motion up 2 folder levels. Changes the working directory to this new binder.

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

Notes:

More often than not there is no demand to change the working directory nevertheless in that location are applications that specifically require yous to set the working directory to their binary binder otherwise they will run. After running this blazon of application the Dwelling variable allows you lot to return to your scripts home folder.

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

  • Each test is displayed and paused.
  • Check the total paths displayed correspond to expected results.
test2.bat
@repeat off rem ### working directory current folder  pushd %~dp0  rem #------Test code ----------- ready Abode=%CD% echo A) Command used was HOME=%%CD%% repeat Surroundings varailbe Abode is %HOME% echo The current working directory is %CD% repeat. pause  CD www repeat B) Command used was CD www echo Environment varailbe Abode is %HOME% echo The current working directory is %CD% echo. intermission  CD ..\..\ echo C) Command used was ..\..\ echo Surround varailbe Domicile is %HOME% repeat The electric current working directory is %CD% echo. pause  CD %HOME%\core\apache2 echo D) Command used was CD %%Abode%%\core\apache2 echo Environment varailbe Habitation is %HOME% repeat The current working directory is %CD% repeat. pause  rem #------ Stop exam 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 motility file, copy copy file, ren rename files, del deleted file, direction operator > to create a file and the management 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 be before attempting to create it. If the folder does not exist it is create using command md (brand directory)

B) The repeat command and redirection operator > writes text to the named file. The named file is either created if information technology does not exist or overwrites an existing file. The redirection operators >> append text to an existing file. The special control echo. (note no space between echo and the full cease) 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.

  • motion 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 motion and copy output confirmation text. This text can be suppressed by redirecting output to the null folder using the redirection operator >>naught.

D) E) The command rd (remove directory) deletes the named binder. Before a folder tin be deleted it must exist 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
@repeat off rem ### working directory current folder  pushd %~dp0  rem #------Test lawmaking ----------- ready HOME=%CD%  echo A) Creating folders IF Non EXIST aaa md aaa IF Not EXIST bbb\ccc md bbb\ccc echo Check folders created pause repeat.   echo B) Creating files in folder aaa repeat. > aaa\z_test1.txt echo Line i > aaa\z_test2.txt echo Line two >> aaa\z_test2.txt echo Check files created suspension echo.   echo C) Moving, copying and renaming files motility 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 Bank check files moved, copied and renamed pause echo.   echo D) Deleting folders rd   aaa rd   bbb\ccc echo Fails because folders not empty suspension echo.   repeat Eastward) 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 intermission echo.   rem #------ Stop examination code ------  rem ### restore original working directory popd  pause                

IF and IF ELSE command

Perform conditional processing in batch programs.

The basic IF control syntax is shown beneath.

IF [NOT] ERRORLEVEL number control IF [Non] string1==string2 command IF [Not] Be filename control  If (condition) (command1) If (condition) (command1) Else (command2)        

The IF control can utilize compound commands statements, a single command is replaced with several commands seperated past 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 i line as prove. However the & operator is not required when the lawmaking is written in a block. The following 2 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 non exist creating file & echo Line i > z_test4.txt)        

B) "IF" written as a cake:

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 i > z_test4.txt )        

Set /p command - user and file input

The SET command displays, sets, or removes surroundings variables. Changes made with Fix will remain simply for the elapsing of the electric current script session.

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

Comments

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

B) Prompt for user input:
The /P switch allows you to gear up 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 render the variable will be unchanged and a errorlevel will be fix.

The test code can be changed as follows, it uses the goto control 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 post-obit command format:

Set /P Some_Var=<Path_Some_text_file_name.txt                

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

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

The content of file PWD_FILE1 is read into into memory and processed. The get-go line is assigned to variable %%Grand. This variable is used to set the variable MYSQL_PWD2 which comletes the control.

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
@repeat off rem ### working directory current folder  pushd %~dp0  rem #------Test code ----------- set up Dwelling house=%CD%  repeat A) Setting countersign file path set PWD_FILE1=%HOME%\htpasswd\mysql\passwd.txt set PWD_FILE2=%Abode%\htpasswd\mysql\passwd.txt set PWD_FILE2= echo Password file %%PWD_FILE1%% is %PWD_FILE1% echo Password file %%PWD_FILE2%% removed ..%PWD_FILE2%.. intermission echo.  repeat B) Prompt for user input Set /P UserInput=Please enter yeah or no  || Prepare UserInput=NothingEntered If "%UserInput%"=="NothingEntered" Exit If /i "%UserInput%"=="no" Exit If /i "%UserInput%"=="yes" echo OK next test pause repeat.  echo C) Getting MySQL password from file ready /p MYSQL_PWD=<%PWD_FILE1% echo MySQL Countersign = %MYSQL_PWD% echo. interruption  echo D) Alternative get MySQL countersign from file FOR /F %%G IN (%PWD_FILE1%) Exercise prepare MYSQL_PWD2=%%Chiliad repeat MySQL Countersign = %MYSQL_PWD2% echo. break  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 at present know what to search for on the Cyberspace.

There is 1 control (FOR /F) that is extremely useful and is worth expanding in details this is covered on page . it allows you to easily laissez passer parameters between batch files and applications run from a batch file.


--oOo--

fulleryoughter.blogspot.com

Source: http://www.uniformserver.com/ZeroXI_documentation/batch_files.html

0 Response to "Batch File Read File Contents Into Variable"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel