window上面的bat脚本

在开发的过程总是有一些重复性的工作要做,比如调试过程版本的升级,设备日志的获取,对于有adb的嵌入式设备其实是很方便的,输入一些命令即可,但是再配合bat脚本就更加方便了,一个双击就完事。

我们的目的很简单,安装/更新一个apk,或者获取设备端的日志

先来了解几个bat脚本里面常用的命令

rem注释

bat脚本以rem开头的表示注释信息

rem 这是一个测试脚本

set

set即设置/定义变量

set dev_desc=连接设备
set dev_status=0

可以赋中文/英文/数字都可以

调用的时候使用前后%%

echo %dev_desc% [%conn_cnt%]...

执行数字表达式
当我们要对变量进行数字运算时,不能直接+/-,需要用到set命令,而且要在前面加上/a,如下:

set /a dev_status = %dev_status% + 1

错误

dev_status = %dev_status% + 1
或者:
set dev_status = %dev_status% + 1

if

判断语句(EQU:等于,NEQ:不等于,LSS:小于,LEQ:小于或等于,GTR:大于 ,GEQ:大于或等于)英文单词的大小写都可以

set dev_status=0
if "%dev_status%" EQU "1" (
  echo 1
) else (
  echo 2
)

:func

定义函数,很多时候我们需要定义一个函数,给别人进行调用,使用:开始,goto :eof为结束。

rem delay sometimes in seconds specified by param 1
:sleep
  ping 1.1 > nul
goto :eof

有时候我们会向函数传递一些参数,可以使用%1 %2...来进行获取第几个参数

rem delay sometimes in seconds specified by param 1
:sleep
  set /a cnt=1+%1
  ping 1.1 -n %cnt% > nul
goto :eof

别人要调用这个函数只需要用call:func即可
https://blog.csdn.net/peng_cao/article/details/73999076

函数的使用还有很多,如使用%~1改变传入参数的值

@echo off

setlocal enabledelayedexpansion

set dev_status=0
set test=2

call :getDevConnStatus dev_status

rem 使用!var!引用改变后的变量值
if !dev_status! equ 0 (
  echo 1
) else (
  echo 2
)
goto :eof

rem get the device status to param 1
:getDevConnStatus
  
  if %test% equ 1 (
    set /a "%~1=1"
    echo 3
  ) else (
    set /a "%~1=0"
    echo 4
  )
goto :eof

dev_status为传入函数的参数,在函数内部可以通过set /a "%~1=?"将其值改变。

setlocal

开始与终止批处理文件中环境改动的本地化操作。在执行 Setlocal 之后所做的环境改动只限于批处理文件。要还原原先的设置,必须执行 Endlocal。达到批处理文件结尾时,对于该批处理文件的每个尚未执行的 Setlocal 命令,都会有一个隐含的 Endlocal 被执行。Endlocal结束批处理文件中环境改动的本地化操作。

实例1:

@echo off
set a=4
set a=5&echo %a%
pause

输出结果为

4

实例2:
设置本地为延迟扩展

@echo off
setlocal enabledelayedexpansion
set a=4
set a=5&echo !a!
pause

输出结果为

5

由于启动了变量延迟,所以批处理能够感知到动态变化,即不是先给该行变量赋值,而是在运行过程中给变量赋值,因此此时a的值就是5了

实例3:
保护局部变量

rem delay sometimes in seconds specified by param 1
:sleep
  setlocal
  set /a cnt=1+%1
  ping 1.1 -n %cnt% > nul
  endlocal
goto :eof

https://blog.csdn.net/fanghongxia2008/article/details/79708881

for

for使用也是比较常用的一种语句
在cmd窗口中:for %I in (command1) do command2
在批处理文件中:for %%I in (command1) do command2

set dev_status=0

call :getDevConnStatus dev_status

rem 使用!var!引用改变后的变量值
if !dev_status! equ 0 (
  goto CONN_DEV
)
    
rem get the device status to param 1
:getDevConnStatus
  set /a "%~1=0"
  for /f "skip=1 tokens=2" %%i in ('adb devices') do (
    if %%i equ device (set /a "%~1=1")
  )
goto :eof

熟悉了上面这些命令后基本上就可以写一些基本的批脚本处理了,这样在重复性的调试过程还是很方便的。

猜你喜欢

转载自blog.csdn.net/weixin_33929309/article/details/87340258