A function is a set of statements organized together to perform a specific task. In batch scripts, a similar approach is adopted to group logical statements together to form a function.
As like any other languages, functions in Batch Script follows the same procedure −
Function Declaration − It tells the compiler about a function's name, return type, and parameters.
Function Definition − It provides the actual body of the function.
Function Definition
In Batch Script, a function is defined by using the label statement. When a function is newly defined, it may take one or several values as input 'parameters' to the function, process the functions in the main body, and pass back the values to the functions as output 'return types'.
Every function has a function name, which describes the task that the function performs. To use a function, you "call" that function with its name and pass its input values (known as arguments) that matches the types of the function's parameters.
Following is the syntax of a simple function.
:function_name Do_something EXIT /B 0
The function_name is the name given to the function which should have some meaning to match what the function actually does.
The EXIT statement is used to ensure that the function exits properly.
Following is an example of a simple function.
Example
:Display SET /A index=2 echo The value of index is %index% EXIT /B 0
Calling a Function
A function is called in Batch Script by using the call command. Following is the syntax.
Syntax
call :function_name
Following example shows how a function can be called from the main program.
Example
@echo off SETLOCAL CALL :Display EXIT /B %ERRORLEVEL% :Display SET /A index=2 echo The value of index is %index% EXIT /B 0
One key thing to note when defining the main program is to ensure that the statement EXIT /B %ERRORLEVEL% is put in the main program to separate the code of the main program from the function.
Output
The above command produces the following output.
The value of index is 2
Functions with Parameters
Functions can work with parameters by simply passing them when a call is made to the function.
Syntax
Call :function_name parameter1, parameter2… parametern
The parameters can then be accessed from within the function by using the tilde (~) character along with the positional number of the parameter.
Following example shows how a function can be called with parameters.
Example
@echo off SETLOCAL CALL :Display 5 , 10 EXIT /B %ERRORLEVEL% :Display echo The value of parameter 1 is %~1 echo The value of parameter 2 is %~2 EXIT /B 0
As seen in the above example, ~1 is used to access the first parameter sent to the function, similarly ~2 is used to access the second parameter.
Output
The above command produces the following output.
The value of parameter 1 is 5 The value of parameter 2 is 10
Functions with Return Values
Functions can work with return values by simply passing variables names which will hold the return values when a call is made to the function as shown below
Syntax
Call :function_name value1, value2… valuen
The return values are set in the function using the set command and the tilde(~) character along with the positional number of the parameter.
Following example shows how a function can be called with return values.
Example
@echo off SETLOCAL CALL :SetValue value1,value2 echo %value1% echo %value2% EXIT /B %ERRORLEVEL% :SetValue set "%~1 = 5" set "%~2 = 10" EXIT /B 0
Output
The above command produces the following output.
5 10
Local Variables in Functions
Local variables in functions can be used to avoid name conflicts and keep variable changes local to the function. The SETLOCAL command is first used to ensure the command processor takes a backup of all environment variables. The variables can be restored by calling ENDLOCAL command. Changes made in between are local to the current batch script. ENDLOCAL is automatically called when the end of the batch file is reached, i.e. by calling GOTO:EOF.
Localizing variables with SETLOCAL allows using variable names within a function freely without worrying about name conflicts with variables used outside the function.
Following example shows how local variables can be used in functions.
Example
@echo off set str = Outer echo %str% CALL :SetValue str echo %str% EXIT /B %ERRORLEVEL% :SetValue SETLOCAL set str = Inner set "%~1 = %str%" ENDLOCAL EXIT /B 0
Output
In the above program, the variable ‘str’ is being localized in the function SetValue. Thus even though the str value is being returned back to the main function, the value of str in the main function will not be replaced by the value being returned from the function.
The above command produces the following output.
Outer Outer
Recursive Functions
The ability to completely encapsulate the body of a function by keeping variable changes local to the function and invisible to the caller. We can now have the ability to call a function recursively making sure each level of recursion works with its own set of variables even though variable names are being reused.
Following example shows how recursive functions can be used.
Example
The example shows how to calculate a Fibonacci number recursively. The recursion stops when the Fibonacci algorism reaches a number greater or equal to a given input number. The example starts with the numbers 0 and 1, the :myFibo function calls itself recursively to calculate the next Fibonacci number until it finds the Fibonacci number greater or equal to 1000000000.
The first argument of the myFibo function is the name of the variable to store the output in. This variable must be initialized to the Fibonacci number to start with and will be used as current Fibonacci number when calling the function and will be set to the subsequent Fibonacci number when the function returns.
@echo off set "fst = 0" set "fib = 1" set "limit = 1000000000" call:myFibo fib,%fst%,%limit% echo.The next Fibonacci number greater or equal %limit% is %fib%. echo.&pause&goto:eof :myFibo -- calculate recursively :myFibo -- calculate recursively the next Fibonacci number greater or equal to a limit SETLOCAL set /a "Number1 = %~1" set /a "Number2 = %~2" set /a "Limit = %~3" set /a "NumberN = Number1 + Number2" if /i %NumberN% LSS %Limit% call:myFibo NumberN,%Number1%,%Limit% (ENDLOCAL IF "%~1" NEQ "" SET "%~1 = %NumberN%" )goto:eof
Output
The above command produces the following output.
The next Fibonacci number greater or equal 1000000000 is 1134903170.
Creating Files
The creation of a new file is done with the help of the redirection filter >. This filter can be used to redirect any output to a file. Following is a simple example of how to create a file using the redirection command.
Example
@echo off echo "Hello">C:\new.txt
Output
If the file new.txt is not present in C:\, then it will be created with the help of the above command.
Writing to Files
Content writing to files is also done with the help of the redirection filter >. This filter can be used to redirect any output to a file. Following is a simple example of how to create a file using the redirection command to write data to files.
Example
@echo off dir C:\>C:\new.txt
The above code snippet first uses the DIR command to get the directory listing of the entire C:\ . It then takes that output and with the help of the redirection command sends it to the file new.txt.
Output
If you open up the file new.txt on your C drive, you will get the contents of your C drive in this file. Following is a sample output.
Volume in drive C is Windows8_OS Volume Serial Number is E41C-6F43 Directory of C:\ 12/22/2015 09:02 PM <DIR> 01 - Music 06/14/2015 10:31 AM <DIR> 02 - Videos 09/12/2015 06:23 AM <DIR> 03 - Pictures 12/17/2015 12:19 AM <DIR> 04 - Software 12/15/2015 11:06 PM <DIR> 05 - Studies 12/20/2014 09:09 AM <DIR> 06 - Future 12/20/2014 09:07 AM <DIR> 07 - Fitness 09/19/2015 09:56 AM <DIR> 08 - Tracking 10/19/2015 10:28 PM <DIR> 09 – Misc
Appending to Files
Content writing to files is also done with the help of the double redirection filter >>. This filter can be used to append any output to a file. Following is a simple example of how to create a file using the redirection command to append data to files.
Example
@echo off echo "This is the directory listing of C:\ Drive">C:\new.txt dir C:\>>C:\new.txt
In the above example, you can see that the first echo command is used to create the file using the single redirection command whereas the DIR command is outputted to the file using the double redirection filter.
Output
If you open the file new.txt on your C drive, you will get the contents of your C drive in this file plus the string “This is the directory listing of C:\ Drive” . Following is a sample output.
"This is the directory listing of C:\ Drive" Volume in drive C is Windows8_OS Volume Serial Number is E41C-6F43 Directory of C:\ 12/22/2015 09:02 PM <DIR> 01 - Music 06/14/2015 10:31 AM <DIR> 02 - Videos 09/12/2015 06:23 AM <DIR> 03 - Pictures 12/17/2015 12:19 AM <DIR> 04 - Software 12/15/2015 11:06 PM <DIR> 05 - Studies 12/20/2014 09:09 AM <DIR> 06 - Future 12/20/2014 09:07 AM <DIR> 07 - Fitness 09/19/2015 09:56 AM <DIR> 08 - Tracking 10/19/2015 10:28 PM <DIR> 09 – Misc
Reading from Files
Reading of files in a Batch Script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. Since there is a no direct command to read text from a file into a variable, the ‘for’ loop needs to be used to serve this purpose.
Let’s look at an example on how this can be achieved.
Example
@echo off FOR /F "tokens=* delims=" %%x in (new.txt) DO echo %%x
The delims parameter is used to break up the text in the file into different tokens or words. Each word or token is then stored in the variable x. For each word which is read from the file, an echo is done to print the word to the console output.
Output
If you consider the new.txt file which has been considered in previous examples, you might get the following output when the above program is run.
"This is the directory listing of C:\ Drive" Volume in drive C is Windows8_OS Volume Serial Number is E41C-6F43 Directory of C:\ 12/22/2015 09:02 PM <DIR> 01 - Music 06/14/2015 10:31 AM <DIR> 02 - Videos 09/12/2015 06:23 AM <DIR> 03 - Pictures 12/17/2015 12:19 AM <DIR> 04 - Software 12/15/2015 11:06 PM <DIR> 05 - Studies 12/20/2014 09:09 AM <DIR> 06 - Future 12/20/2014 09:07 AM <DIR> 07 - Fitness 09/19/2015 09:56 AM <DIR> 08 - Tracking 10/19/2015 10:28 PM <DIR> 09 – Misc
Deleting Files
For deleting files, Batch Script provides the DEL command.
Syntax
DEL [/P] [/F] [/S] [/Q] [/A[[:]attributes]] names
Following are the description of the options which can be presented to the DEL command.
S.No. | Options & Description |
---|---|
1. |
Names Specifies a list of one or more files or directories. Wildcards may be used to delete multiple files. If a directory is specified, all files within the directory will be deleted |
2. |
/P Prompts for confirmation before deleting each file. |
3. |
/F Force deletes of read-only files. |
4. |
/S Deletes specified files from all subdirectories. |
5. |
/Q Quiet mode, do not ask if ok to delete on global wildcard. |
6. |
/A Selects files to delete based on attributes. |
7. |
attributes R Read-only files, S System files, H Hidden files, A Files ready for archiving - Prefix meaning not |
Following examples show how the DEL command can be used.
Examples
del test.bat
The above command will delete the file test.bat in the current directory, if the file exists.
del c:\test.bat
The above command will delete the file C:\test.bat in the current directory, if the file exists.
del c:\*.bat
The * (asterisks) is a wild character. *.bat indicates that you would like to delete all bat files in the c:\directory.
del c:\?est.tmp
The ? (question mark) is a single wild character for one letter. The use of this command in the above example will delete any file ending with "est.tmp", such as pest.tmp or test.tmp.
Renaming Files
For renaming files, Batch Script provides the REN or RENAME command.
Syntax
RENAME [drive:][path][directoryname1 | filename1] [directoryname2 | filename2]
Let’s take a look at some examples of renaming files.
Examples
rename *.txt *.bak
The above command will rename all text files to files with .bak extension.
rename "TESTA.txt" "TESTB.txt"
The above command will rename the file TESTA.txt to TESTB.txt.
Moving Files
For moving files, Batch Script provides the MOVE command.
Syntax
MOVE [/Y | /-Y] [drive:][path]filename1[,...] destination
Following are the description of the options which can be presented to the DEL command.
S.No. | Options & Description |
---|---|
1. |
[drive:][path]filename1 Specifies the location and name of the file or files you want to move |
2. |
destination Specifies the new location of the file. Destination can consist of a drive letter and colon, a directory name, or a combination. If you are moving only one file, you can also include a filename if you want to rename the file when you move it. |
3. |
[drive:][path]dirname1 Specifies the directory you want to rename. |
4. |
dirname2 Specifies the new name of the directory. |
5. |
/Y Suppresses prompting to confirm you want to overwrite an existing destination file. |
6. |
/-Y Causes prompting to confirm you want to overwrite an existing destination file. |
Let’s look at some examples of renaming files.
Examples
move c:\windows\temp\*.* c:\temp
The above command will move the files of c:\windows\temp to the temp directory in root.
move new.txt, test.txt c:\example
The above command will move the files new.txt and test.txt into the c:\example folder.
Files Pipes
The pipe operator (|) takes the output (by default, STDOUT) of one command and directs it into the input (by default, STDIN) of another command. For example, the following command sorts the contents of the directory C:\
dir C:\ | sort
In this example, both commands start simultaneously, but then the sort command pauses until it receives the dir command's output. The sort command uses the dir command's output as its input, and then sends its output to handle 1 (that is, STDOUT).
Following is another example of the pipe command. In this example, the contents of the file C:\new.txt are sent to the sort command through the pipe filter.
@echo off TYPE C:\new.txt | sort
Combining Commands with Redirection Operators
Usually, the pipe operator is used along with the redirection operator to provide useful functionality when it comes to working with pipe commands.
For example, the below command will first take all the files defined in C:\, then using the pipe command, will find all the files with the .txt extension. It will then take this output and print it to the file AllText.txt.
dir C:\ | find "txt" > AllText.txt
Using Multiple Pipe Commands
To use more than one filter in the same command, separate the filters with a pipe (|). For example, the following command searches every directory on drive C:, finds the file names that include the string "Log", and then displays them in one Command Prompt window at a time −
dir c:\ /s /b | find "TXT" | more
Following are some examples of how the pipe filter can be used.
Examples
The following example send’s the list of all running tasks using the tasklist command and sends the output to the find command. The find command will then find all processes which are of the type notepad and display them in the command prompt.
tasklist | find "notepad"
Output
Following is a sample output.
notepad.exe 1400 Console 1 8,916 K notepad.exe 4016 Console 1 11,200 K notepad.exe 1508 Console 1 8,720 K notepad.exe 4076 Console 1 8,688 K
The following example send’s the list of all running tasks using the tasklist command and sends the output to the more command. The more command will then display the lists of running tasks one page at a time.
Example
tasklist | more
Output
Image Name PID Session Name Session# Mem Usage ====================== ================ =========== ============ System Idle Process 0 Services 0 4 K System 4 Services 0 276 K smss.exe 344 Services 0 1,060 K csrss.exe 524 Services 0 4,188 K csrss.exe 608 Console 1 58,080 K wininit.exe 616 Services 0 3,528 K winlogon.exe 644 Console 1 5,636 K services.exe 708 Services 0 7,072 K lsass.exe 716 Services 0 10,228 K svchost.exe 784 Services 0 10,208 K svchost.exe 828 Services 0 7,872 K dwm.exe 912 Console 1 208,316 K nvvsvc.exe 932 Services 0 6,772 K nvxdsync.exe 968 Console 1 16,584 K nvvsvc.exe 976 Console 1 12,780 K svchost.exe 1008 Services 0 20,340 K svchost.exe 224 Services 0 39,740 K svchost.exe 468 Services 0 11,864 K svchost.exe 860 Services 0 11,184 K svchost.exe 232 Services 0 16,992 K wlanext.exe 1168 Services 0 12,840 K -- More --
The following example send’s the list of all running tasks using the tasklist command and sends the output to the find command. The find command will then find all processes which are of the type notepad and then uses the redirection command to send the content to the file tasklist.txt.
Example
tasklist | find "notepad" > tasklist.txt
Output
If you open the file tasklist.txt, you will get the following sample output.
notepad.exe 1400 Console 1 8,916 K notepad.exe 4016 Console 1 11,200 K notepad.exe 1508 Console 1 8,720 K notepad.exe 4076 Console 1 8,688 K
Files Inputs
When a batch file is run, it gives you the option to pass in command line parameters which can then be read within the program for further processing. The batch files parameters can be recalled from within the program using the % operator along with the numeric position of the parameter. Following is how the command line parameters are defined.
- %0 is the program name as it was called.
- %1 is the first command line parameter.
- %2 is the second command line parameter.
- So on till %9.
Let’s take a look at a simple example of how command line parameters can be used.
Example
@echo off echo The first parameter is %1 echo The second parameter is %2 echo The third parameter is %3
Output
If the above code is stored in a file called test.bat and the file is run as
test.bat 5 10 15
then, following will be the output.
The first parameter is 5 The second parameter is 10 The third parameter is 15
Using the SHIFT Operator
One of the limitations of command line arguments is that it can accept only arguments till %9. Let’s take an example of this limitation.
Example
@echo off echo %1 echo %2 echo %3 echo %4 echo %5 echo %6 echo %7 echo %8 echo %9 echo %10
Output
If the above code is stored in a file called test.bat and the file is run as
test.bat a b c d e f g h i j
Then following will be the output.
a b c d e f h i a0
As you can see from the above output, the final value which should be shown as ‘j’ is being shown as a0. This is because there is no parameter known as %10.
This limitation can be avoided by using the SHIFT operator. After your batch file handled its first parameter(s) it could SHIFT them (just insert a line with only the command SHIFT), resulting in %1 getting the value B, %2 getting the value C, etcetera, till %9, which now gets the value J. Continue this process until at least %9 is empty.
Let’s look at an example of how to use the SHIFT operator to overcome the limitation of command line arguments.
Example
@ECHO OFF :Loop IF "%1"=="" GOTO Continue echo %1% SHIFT GOTO Loop :Continue
If the above code is stored in a file called test.bat and the file is run as
test.bat a b c d e f g h i j
Then following will be the output.
a b c d e f h i j
Note
Some characters in the command line are ignored by batch files, depending on the DOS version, whether they are "escaped" or not, and often depending on their location in the command line −
Commas (",") are replaced by spaces, unless they are part of a string in doublequotes.
Semicolons (";") are replaced by spaces, unless they are part of a string in doublequotes.
"=" characters are sometimes replaced by spaces, not if they are part of a string in doublequotes.
The first forward slash ("/") is replaced by a space only if it immediately follows the command, without a leading space.
Multiple spaces are replaced by a single space, unless they are part of a string in doublequotes.
Tabs are replaced by a single space.
Leading spaces before the first command line argument are ignored.
Trailing spaces after the last command line argument are trimmed.
Renaming Folders
For renaming folders, Batch Script provides the REN or RENAME command.
Syntax
RENAME [drive:][path][directoryname1 | filename1] [directoryname2 | filename2]
Let’s look at some examples of renaming folders.
Examples
ren Example Example1
The above command will rename the folder called Example in the current working directory to Example1.
ren C:\Example Example1
The above command will rename the folder called Example in C Drive to Example1.
Moving Folders
For moving folders, Batch Script provides the MOVE command.
Syntax
MOVE [/Y | /-Y] [drive:][path]filename1[,...] destination
Following are the description of the options which can be presented to the DEL command.
S.No. | Options & Description |
---|---|
1. |
[drive:][path]filename1 Specifies the location and name of the file or files you want to move |
2. |
destination Specifies the new location of the file. Destination can consist of a drive letter and colon, a directory name, or a combination. If you are moving only one file, you can also include a filename if you want to rename the file when you move it. |
3. |
[drive:][path]dirname1 Specifies the directory you want to rename. |
4. |
dirname2 Specifies the new name of the directory. |
5. |
/Y Suppresses prompting to confirm you want to overwrite an existing destination file. |
6. |
/-Y Causes prompting to confirm you want to overwrite an existing destination file. |
Let’s look at some examples of moving folders.
Examples
move *.* C:\Example
The above command will move all files from the current directory to the folder C:\Example.
move *.txt C:\Example
The above command will move all files with the txt extension from the current directory to the folder C:\Example.
move C:\old\*.* C:\Example
The above command will move all files from the folder called ‘old’ in C drive to the folder C:\Example.
沒有留言:
張貼留言