DOS Batch - Function Tutorial

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.

TOP
2008-01-01

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:
01.
02.
03.
04.
: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

TOP
2008-01-01

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

TOP
2008-01-01

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: Download: BatchTutoFunc1.bat

01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
@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
  1. going to execute myDosFunc
  2. here the myDosFunc function is executing a group of commands
  3. it could do a lot of things
  4. returned from myDosFunc
  5.  
  6. Press any key to continue . . .

TOP
2008-01-01

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:
01.
02.
03.
call:myDosFunc 100 YeePEE
call:myDosFunc 100 "for me"
call:myDosFunc 100,"for me"

TOP
2008-01-01

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:
01.
02.
03.
04.
05.
: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

TOP
2008-01-01

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: Download: BatchTutoFunc2.bat

01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
@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
  1. going to execute myDosFunc with different arguments
  2.  
  3. here the myDosFunc function is executing a group of commands
  4. it could do 100 of things YeePEE.
  5.  
  6. here the myDosFunc function is executing a group of commands
  7. it could do 100 of things for me.
  8.  
  9. here the myDosFunc function is executing a group of commands
  10. it could do 100 of things for me.
  11.  
  12. here the myDosFunc function is executing a group of commands
  13. it could do 100 of things for.
  14.  
  15. Press any key to continue . . .

TOP
2008-01-01

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:
01.
02.
03.
04.
set "var1=some hopefully not important string"
echo.var1 before: %var1%
call:myGetFunc
echo.var1 after : %var1%
Script:
01.
02.
03.
:myGetFunc    - get a value
set "var1=DosTips"
goto:eof
Script Output:
  Script Output
  1. var1 before: some hopefully not important string
  2. var1 after : DosTips

TOP
2008-01-01

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:
01.
02.
call:myGetFunc var1
echo.var1 after : %var1%
Script:
01.
02.
03.
:myGetFunc    - passing a variable by reference
set "%~1=DosTips"
goto:eof
Script Output:
  Script Output
  1. var1 after : DosTips

TOP
2008-01-01

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: Download: BatchTutoFunc3.bat

01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
@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
  1. var1 before: CmdTips
  2. var1 after : DosTips
  3.  
  4. Press any key to continue . . .

TOP
2008-01-01

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: Download: BatchTutoFunc4.bat

01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
@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
  1. aStr before: Expect no changed, even if used in function
  2. var1 before: No change for this one. Now what?
  3. aStr after : Expect no changed, even if used in function
  4. var1 after : No change for this one. Now what?
  5.  
  6. Press any key to continue . . .

TOP
2008-01-01

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: Download: BatchTutoFunc5.bat

01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
@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
  1. aStr before: Expect no changed, even if used in function
  2. var1 before: Expect changed
  3. aStr after : Expect no changed, even if used in function
  4. var1 after : DosTips
  5.  
  6. Press any key to continue . . .

TOP
2008-01-01

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 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 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: Download: BatchTutoFuncRecurs.bat

01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
@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
  1. The next Fibonacci number greater or equal 1000000000 is 1134903170.
  2.  
  3. Press any key to continue . . .

TOP
2008-01-01

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: Download: BatchFunctionTmpl.bat

01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
: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

DOS批处理 - 函数教程的更多相关文章

  1. DOS批处理高级教程(还不错)(转)

    前言 目录 第二节 常用特殊符号     1.@  命令行回显屏蔽符     2.%  批处理变量引导符     3.>   输出重定向符     4.>>  输出重定向符     ...

  2. DOS批处理高级教程

    转载-->http://blog.csdn.net/lanbing510/article/details/7461073 前言 本教程主要引用伤脑筋版主的系列文章,同时参考引用[英雄]教程等其他 ...

  3. cocos2d-x教程3:用php或DOS批处理命令来转换文件和解压缩zip

    在cocos2d-x使用中,须要不停的转换文件和压缩或解压文件.假设全人工来做,太麻烦了,且easy出错. 我如今把一些用的到批处理贴出来,供大家使用 自己主动把dat文件按数字排序重命名gz.DOS ...

  4. 【转载】BAT 批处理脚本教程

    来源:http://www.cnblogs.com/glaivelee/archive/2009/10/07/1578737.html BAT 批处理脚本 教程   第一章 批处理基础第一节 常用批处 ...

  5. BAT 批处理脚本 教程 【转】

    BAT 批处理脚本 教程 第一章 批处理基础 第一节 常用批处理内部命令简介 批处理定义:顾名思义,批处理文件是将一系列命令按一定的顺序集合为一个可执行的文本文件,其扩展名为BAT或者CMD.这些命令 ...

  6. 转:windows BAT 批处理脚本教程

    转自:http://www.cnblogs.com/mq0036/p/3412171.html BAT 批处理脚本教程 第一章 批处理基础第一节 常用批处理内部命令简介 批处理定义:顾名思义,批处理文 ...

  7. 用DOS批处理实现FTP自动上传、下载、清理文件

    用DOS批处理实现FTP自动上传.下载.清理文件 最近好像特别的忙,好久没来写点东西了,今天写了一个利用批处理程序完成FTP自动上传.下载.清理文件的程序.赶紧 记录下来,以备日后之用.功能介绍:自动 ...

  8. DOS批处理的字符串功能

    原文:DOS批处理的字符串功能 DOS批处理的字符串功能 批处理有着具有非常强大的字符串处理能力,其功能绝不低于C语言里面的字符串函数集.批处理中可实现的字符串处理功能有:截取字符串内容.替换字符串特 ...

  9. 利用DOS批处理实现定时关机操作

    10月1放假回来,寝室晚上10:30就停电了,最无法让人理解的是第二天早上8:00才来电.原来晚上电脑都是不关机的,开着WiFi一直到天亮,可是现在不行了,电脑如果一直开着第二天早上起来电脑肯定没电, ...

随机推荐

  1. python-day13--装饰器

    1.开放封闭的原则: 1.对扩展是开放的 为什么要对扩展开放呢? 我们说,任何一个程序,不可能在设计之初就已经想好了所有的功能并且未来不做任何更新和修改.所以我们必须允许代码扩展.添加新功能. 2.对 ...

  2. Sunday算法[原创]

    一.应用: 同样的,sunday算法也是在一个字符串中查找另一个字符串出现的首地址,是Daniel M.Sunday于1990年提出的,从销量上讲,Sunday>BM>KMP,是这类问题的 ...

  3. POJ-2251 Dungeon Master (BFS模板题)

    You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of un ...

  4. ORACLE workflow审批界面显示附件信息和附件的下载链接(转)

    原文: ORACLE workflow审批界面显示附件信息和附件的下载链接 EBS获取附件URL 代码如下: CREATE OR REPLACE PACKAGE cux_attachment_util ...

  5. spring boot 学习番外篇:超快速项目初始化

    超快速完成 Spring Boot 项目初始化 最近,在浏览 SPRING 官网时,发现一个超级方便的小工具,可以帮助我们快速创建一个 Spring Boot 项目,前提就是你能连接互联网. 依赖 支 ...

  6. httpclient cookie相关介绍

    http状态管理 cookie是HTTP代理和目标服务器可以交流保持回话的状态信息的令牌或短包. httpclient使用Cookie接口来代表抽象的cookie令牌,在它的简单形式中http的coo ...

  7. 远程桌面连接 [Content] 出现身份验证错误。 要求的函数不受支持

    [Window Title] 远程桌面连接 [Content] 出现身份验证错误. 要求的函数不受支持 以上是我远程得时候报的错.   下面直接上  最NB得解决方案.不管用直接在下面评论 通过管理控 ...

  8. ehlib 安装

    EhLibProjGroup110.groupproj,依次编译所有的包,再安装所有的dcl设计时包. == EhLib 7.0.133 Full Source 使用安装器EhLibInstaller ...

  9. 关于edge detecte

    1.注意render Texture 双击render Texture ,要勾选 use viewport dimensions,否则出现边框和模型不合的情况 2.注意edge detecte 的状态 ...

  10. String,StringBuilder和StringBuffer的特点和使用场景

    这三个类是平时开发中经常遇到的,主要差别是运行速度和线程安全,使用起来String最方便了,另外两个稍微复杂一些. 从运行速度角度看,StringBuilder>StringBuffer> ...