DOS批处理 函数定义与用法_DOS/BAT

What it is, why it`s important and how to write your own.

Description: The assumption is: A batch script snippet can be named a function when:

1.... it has a callable entrance point.
2.... on completion execution continues right after the command that initially called the function.
3.... it works the same no matter from where it`s being called, even when it calls itself recursively.
4.... the variables used within a function do not conflict with variables outside the function.
5.... it exchanges data with the calling code strictly through input and output variables or a return code.

The benefits behind functions are:

1.Keep the main script clean
2.Hide complexity in reusable functions
3.Test functions independently from the main script
4.Add more functionality to your batch script simply by adding more functions at the bottom
5.Don`t worry about the function implementation, just test it and use it
 
Create a Function What is a function?
Call a Function How to invoke a function?
Example - Calling a Function An Example showing how it works.
Passing Function Arguments How to pass arguments to the function?
Parsing Function Arguments How to retrieve function arguments within the function?
Example - Function with Arguments An Example showing how it works.
Returning Values the Classic Way The classic way of returning values and the limitations.
Returning Values via References Let the caller determine how to return the function result and avoid the need of dedicated variables.
Example - Returning Values using Variable Reference An Example showing how it works.
Local Variables in Functions How to avoid name conflicts and keep variable changes local to the function?
Returning Local Variables How to pass return values over the ENDLOCAL barrier?
Recursive Functions Tadaaah!!!
Summary Defining a standard format for a DOS batch function
DOS Batch - Function Tutorial What it is, why it`s important and how to write your own.

Create a Function - What is a function
Description: In DOS you write a function by surrounding a group of command by a label and a GOTO:EOF command. A single batch file can contain multiple functions defined like this. The label becomes the function name.
Script:

复制代码 代码如下:

:myDosFunc    - here starts my function identified by it`s label
echo. here the myDosFunc function is executing a group of commands
echo. it could do a lot of things
GOTO:EOF

 

Call a Function - How to invoke a function
Description: A function can be called with the CALL command followed by the function label.
Script: 01.
 call:myDosFunc

Example - Calling a Function - An Example showing how it works
Description: The use of batch functions will divide the script into two sections.

1.The main script: starting at line 1 ending with a GOTO:EOF command that terminates the script.
2.The function section: filling the second half of the batch file with one or more functions to be callable from the main script.
 
Script:

复制代码 代码如下:

@echo off
echo.going to execute myDosFunc
call:myDosFunc
echo.returned from myDosFunc

echo.&pause&goto:eof

::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------

:myDosFunc    - here starts my function identified by it`s label
echo.  here the myDosFunc function is executing a group of commands
echo.  it could do a lot of things
goto:eof

 
Script Output:   Script Output 
going to execute myDosFunc
  here the myDosFunc function is executing a group of commands
  it could do a lot of things
returned from myDosFunc
Press any key to continue . . .
 
Passing Function Arguments - How to pass arguments to the function
Description: Just as the DOS batch file itself can have arguments, a function can be called with arguments in a similar way. Just list all arguments after the function name in the call command.
Use a space or a comma to separate arguments.
Use double quotes for string arguments with spaces.
Script:

复制代码 代码如下:

call:myDosFunc 100 YeePEE
call:myDosFunc 100 "for me"
call:myDosFunc 100,"for me"

 
Parsing Function Arguments - How to retrieve function arguments within the function
Description: Just as the DOS batch file itself retrieves arguments via %1 ⦠%9 a function can parse it`s arguments the same way. The same rules apply.
Let`s modify our previews example to use arguments.
To strip of the double quotes in an arguments value the tilde modifier, i.e. use %~2 instead of %2.
Script:

复制代码 代码如下:

 :myDosFunc    - here starts myDosFunc identified by it`s label
echo.
echo. here the myDosFunc function is executing a group of commands
echo. it could do %~1 of things %~2.
goto:eof

 
Example - Function with Arguments - An Example showing how it works
Description: The following example demonstrates how to pass arguments into a DOS function. The :myDosFunc function is being called multiple times with different arguments.

Note: The last call to myDosFunc doesn`t use double quotes for the second argument. Subsequently "for" and "me" will be handled as two separate arguments, whereas the third argument "me" is not being used within the function.
Script:

复制代码 代码如下:

 @echo off
echo.going to execute myDosFunc with different arguments
call:myDosFunc 100 YeePEE
call:myDosFunc 100 "for me"
call:myDosFunc 100,"for me"
call:myDosFunc 100,for me
echo.&pause&goto:eof

::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------

:myDosFunc    - here starts my function identified by it's label
echo.
echo. here the myDosFunc function is executing a group of commands
echo. it could do %~1 of things %~2.
goto:eof

 
Script Output:   Script Output 
going to execute myDosFunc with different arguments
 
 here the myDosFunc function is executing a group of commands
 it could do 100 of things YeePEE.
 
 here the myDosFunc function is executing a group of commands
 it could do 100 of things for me.
 
 here the myDosFunc function is executing a group of commands
 it could do 100 of things for me.
 
 here the myDosFunc function is executing a group of commands
 it could do 100 of things for.
 
Press any key to continue . . .
 

Returning Values the Classic Way - The classic way of returning values and the limitations
Description: The CALL command doesn`t support return values as known by other programming languages.
The classic walkaround is to have the function store the return value into a environment variable. The calling script can use this variable when the function returns. The :myGetFunc function below demonstrates how the variable var1 gets the "DosTips" string assigned which can then be used in the calling function.

Note: The var1 variable is reserved for this particular function. Any data stored in var1 by the calling function before calling :myGetVar will be overwritten.
Usage:

复制代码 代码如下:

 set "var1=some hopefully not important string"
echo.var1 before: %var1%
call:myGetFunc
echo.var1 after : %var1%

 
Script:

复制代码 代码如下:

 :myGetFunc    - get a value
set "var1=DosTips"
goto:eof

 
Script Output:   Script Output 
var1 before: some hopefully not important string
var1 after : DosTips
 
Returning Values via References - Let the caller determine how to return the function result and avoid the need of dedicated variables
Description: Instead of using "global" variables for return value, the function can use one of it`s arguments as variable reference. The caller can then pass a variable name to the function and the function can store the result into this variable making use of the command line expansion of the command processor:

Note: The var1 variable is not reserved for this articular function. Any variable can be passed to the function the caller has full control.
Usage:

复制代码 代码如下:

 call:myGetFunc var1
echo.var1 after : %var1%

 
Script:

复制代码 代码如下:

 :myGetFunc    - passing a variable by reference
set "%~1=DosTips"
goto:eof

 
Script Output:   Script Output 
var1 after : DosTips
 
Example - Returning Values using Variable Reference - An Example showing how it works
Description: This code shows how the var1 variable is being passed into a :myGetFunc function simply by passing the variable name. Within the :myGetFunc function the command processor works like this:
1.Reads the set command into memory: set "%~1=DosTips"
2.Expand the variables, i.e. %~1 like this: set "var1=DosTips"
3.Finally execute the command and assign the new string to var1
 
Script:

复制代码 代码如下:

 @echo off

set "var1=CmdTips"
echo.var1 before: %var1%
call:myGetFunc var1
echo.var1 after : %var1%

echo.&pause&goto:eof

::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------

:myGetFunc    - passing a variable by reference
set "%~1=DosTips"
goto:eof

 
Script Output:   Script Output 
var1 before: CmdTips
var1 after : DosTips
 
Press any key to continue . . .
 

Local Variables in Functions - How to avoid name conflicts and keep variable changes local to the function
Description: The SETLOCAL causes the command processor to backup all environment variables. The variables can be restored by calling ENDLOCAL. Changes made im between are local to the current batch. ENDLOCAL is automatically being 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.
Script:

复制代码 代码如下:

 @echo off

set "aStr=Expect no changed, even if used in function"
set "var1=No change for this one.  Now what?"
echo.aStr before: %aStr%
echo.var1 before: %var1%
call:myGetFunc var1
echo.aStr after : %aStr%
echo.var1 after : %var1%

echo.&pause&goto:eof

::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------

:myGetFunc    - passing a variable by reference
SETLOCAL
set "aStr=DosTips"
set "%~1=%aStr%"
ENDLOCAL
goto:eof

 
Script Output:   Script Output 
aStr before: Expect no changed, even if used in function
var1 before: No change for this one.  Now what?
aStr after : Expect no changed, even if used in function
var1 after : No change for this one.  Now what?
 
Press any key to continue . . .
 
Returning Local Variables - How to pass return values over the ENDLOCAL barrier
Description: The question is: When localizing a function via SETLOCAL and ENDLOCAL, how to return a value that was calculated before executing ENDLOCAL when ENDLOCAL restores all variables back to its original state?
The answer comes with "variable expansion". The command processor expands all variables of a command before executing the command. Letting the command processor executing ENDLOCAL and a SET command at once solves the problem. Commands can be grouped within brackets.
Script:

复制代码 代码如下:

 @echo off

set "aStr=Expect no changed, even if used in function"
set "var1=Expect changed"
echo.aStr before: %aStr%
echo.var1 before: %var1%
call:myGetFunc var1
echo.aStr after : %aStr%
echo.var1 after : %var1%

echo.&pause&goto:eof

::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------

:myGetFunc    - passing a variable by reference
SETLOCAL
set "aStr=DosTips"
( ENDLOCAL
    set "%~1=%aStr%"
)
goto:eof

:myGetFunc2    - passing a variable by reference
SETLOCAL
set "aStr=DosTips"
ENDLOCAL&set "%~1=%aStr%"       &rem THIS ALSO WORKS FINE
goto:eof

 
Script Output:   Script Output 
aStr before: Expect no changed, even if used in function
var1 before: Expect changed
aStr after : Expect no changed, even if used in function
var1 after : DosTips
 
Press any key to continue . . .

Recursive Functions - Tadaaah!!!
Description: Being able to completely encapsulate the body of a function by keeping variable changes local to the function and invisible to the caller we are now able to call a function recursively making sure each level of recursion works with its own set of variables even thought variable names are being reused.

Example: The next example below shows how to calculate a Fibonacci number recursively. The recursion ss 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 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.
Script:

复制代码 代码如下:

 @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

::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------

:myFibo  -- calculate recursively the next Fibonacci number greater or equal to a limit
::       -- %~1: return variable reference and current Fibonacci number
::       -- %~2: previous value
::       -- %~3: 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

 
Script Output:   Script Output 
The next Fibonacci number greater or equal 1000000000 is 1134903170.
 
Press any key to continue . . .
 
Summary - Defining a standard format for a DOS batch function
Description: With the information learned in this section we can define a standard format for a DOS batch functions as shown below.
Also check out the rich set of ready to use DOS functions provided by the DosTips.com function library.
Script:

复制代码 代码如下:

 :myFunctionName    -- function description here
::                 -- %~1: argument description here
SETLOCAL
REM.--function body here
set LocalVar1=...
set LocalVar2=...
(ENDLOCAL & REM -- RETURN VALUES
    IF "%~1" NEQ "" SET %~1=%LocalVar1%
    IF "%~2" NEQ "" SET %~2=%LocalVar2%
)
GOTO:EOF

出处http://www.dostips.com/DtTutoFunctions.php

时间: 2024-09-20 09:16:24

DOS批处理 函数定义与用法_DOS/BAT的相关文章

dos下at命令的用法_DOS/BAT

At 列出在指定的时间和日期在计算机上运行的已计划命令或计划命令和程序.必须正在运行"计划"服务才能使用 at 命令. at [\\computername] [[id] [/delete] | /delete [/yes]] at [\\computername] time [/interactive] [/every:date[,...]| /next:date[,...]] command  参数 无 如果在没有参数的情况下使用,则 at 列出已计划的命令. [url=file:

python简单的函数定义和用法实例

  这篇文章主要介绍了python简单的函数定义和用法,实例分析了Python自定义函数及其使用方法,具有一定参考借鉴价值,需要的朋友可以参考下 这里定义了一个温度转换的函数及其用法. ? 1 2 3 4 5 6 7 8 9 def convertTemp(temp, scale): if scale == "c": return (temp - 32.0) * (5.0/9.0) elif scale == "f": return temp * 9.0/5.0 +

浅谈PHP eval()函数定义和用法

eval() 函数把字符串按照 PHP 代码来计算. 该字符串必须是合法的 PHP 代码,且必须以分号结尾. 如果没有在代码字符串中调用 return 语句,则返回 NULL.如果代码中存在解析错误,则 eval() 函数返回 false. 语法 eval(phpcode) 参数 描述 phpcode 必需.规定要计算的 PHP 代码. 提示和注释 注释:返回语句会立即终止对字符串的计算. 注释:该函数对于在数据库文本字段中供日后计算而进行的代码存储很有用. 例子 <?php $string =

DOS批处理高级教程 第二章 DOS循环for命令详解_DOS/BAT

讲FOR之前呢,咋先告诉各位新手朋友,如果你有什么命令不懂,直接在CMD下面输入: name /? 这样的格式来看系统给出的帮助文件,比如for /? 就会把FOR命令的帮助全部显示出来!当然许多菜鸟都看不懂....所以才会有那么多批处理文章!!!!俺也照顾菜鸟,把FOR命令用我自己的方式说明下! 正式开始: 一.基本格式 FOR %%variable IN (set) DO command [command-parameters] %%variable 指定一个单一字母表示可替换的参数. (s

批处理for命令使用指南_DOS/BAT

FOR这条命令基本上都被用来处理文本,但还有其他一些好用的功能! 看看他的基本格式(这里我引用的是批处理中的格式,直接在命令行只需要一个%号) FOR 参数 %%变量名 IN (相关文件或命令) DO 执行的命令 参数:FOR有4个参数 /d   /l   /r   /f   他们的作用我在下面用例子解释 %%变量名 :这个变量名可以是小写a-z或者大写A-Z,他们区分大小写,FOR会把每个读取到的值给他; IN:命令的格式,照写就是了; (相关文件或命令) :FOR要把什么东西读取然后赋值给变

批处理实例代码教程 集合_DOS/BAT

批处理实例代码教程 -------------------------------------------------------------------------------- 批处理程序删除自身.bat echo 有时候我们需要批处理程序在执行完成之后删除自身,可以用 del %0 例: 复制代码 代码如下: @echo off echo 按任意键后我将删除自身 pause del %0 ---------------------------------------------------

dos命令行中cd命令用法_DOS/BAT

显示当前目录名或改变当前目录. CHDIR [/D] [drive:][path] CHDIR [..] CD [/D] [drive:][path] CD [..] .. 指定要改成父目录. 键入 CD drive: 显示指定驱动器中的当前目录. 不带参数只键入 CD,则显示当前驱动器和目录. 使用 /D 开关,除了改变驱动器的当前目录之外, 还可改变当前驱动器. 如果命令扩展被启用,CHDIR 会如下改变: 当前的目录字符串会被转换成使用磁盘名上的大小写.所以, 如果磁盘上的大小写如此,CD

批处理的高级运用技巧_DOS/BAT

批处理的高级运用1 一.简单批处理内部命令  批处理的高级运用!!小技巧哦!!!  批处理大家都很熟悉吧!  下面介绍批处理的几个知识点:  1:巧用FC命令做查木马工具:  首先建立批处理文件atm.bat:写入代码:@echo off  dir c:\windows\system32\*.exe >c:??.txt  dir c:\windows\system32\*.dll >c:??.txt  2:建立批处理文件WLTS.bat 写入代码:@echo off  dir c:\windo

批处理 延时不完全总结_DOS/BAT

1.利用ping命令实现延时,方法巧妙而且可以控制,但精度不高. 如:ping -n 3 127.0.0.1>nul大约可以停顿2秒 -n后的数字是发送包的数目,为暂停秒数加一.此法每秒有0.5%的偏差,时间精度为1秒. @echo off @ping 127.0.0.1 -n 6 >nul start gdh.txt 2.用vbs脚本中的sleep实现,样本代码如下: 缺点:生成临时文件 优点:时间精度为0.001秒,精度高 例子1.vbs cscript 复制代码 代码如下: @echo