bat函數寫法
如下是一個最簡單的函數寫法;以:func
開始以goto:eof
結束。:func
和goto:eof
之間的為函數內容,例如這裡的echo this is a bat func
:func
echo this is a bat func
goto:eof
bat函數調用
寫好了bat函數之後,我們需要調用它。如下代碼片段展示瞭如何在bat腳本中調用函數。其實很簡單,就這一句call:func
即可。
call:func
pause
:func
echo this is a bat func
goto:eof
bat函數返回值
目前我瞭解到的bat函數返回值的獲取有如下兩種方法:
- 使用參數帶回
- 使用全域變量帶回
這裡直接貼上關於bat函數的各種條件的驗證代碼
echo off
color 0d
echo bat Function example
echo =================================
echo ==========Func No paramter ======
echo =================================
echo before call myFuncNoPara
call:myFuncNoPara
echo after call myFuncNoPara
echo =================================
echo ===========Func has paramter=====
echo =================================
echo before call myFuncHasPara
call:myFuncHasPara 123 abc
echo after call myFuncHasPara
echo =================================
echo =======Func with return value====
echo =================================
set return=123
set returnPara=321
echo return:%return%
echo returnPara:%returnPara%
echo befora call myFuncReturnValue
call:myFuncReturnValue returnPara abc
echo after call myFuncReturnValue
echo return:%return%
echo returnPara:%returnPara%
pause
:myFuncNoPara
echo myFuncNoPara enter
echo myFuncNoPara First para:%1
echo myFuncNoPara Second para:%2
echo myFuncNoPara Third para:%3
echo myFuncNoPara exit
goto:eof
:myFuncHasPara
echo myFuncHasPara enter
echo myFuncHasPara First para:%1
echo myFuncHasPara Second para:%2
echo myFuncHasPara Third para:%3
echo myFuncHasPara exit
goto:eof
:myFuncReturnValue
echo myFuncReturnValue
echo myFuncReturnValue First para:%1
echo myFuncReturnValue Second para:%2
set "%~1=%2%"
set return=%2
goto:eof
運行效果圖
沒有留言:
張貼留言