windows bat批处理程序备忘


关闭单条命令回显
命令前加 @

关闭所有命令回显
@echo off

获取参数
%1 %2 %*
%~1 去除引号

多余9个参数时可使用shift /1

将bat所在目录设置为当前目录

%0是当前bat的路径

cd /d %~dp0

设置(环境)变量
set PARAM=ppp

echo %PARAM%

注释
::this is comment
rem this is comment too

调用另一个bat
call other.bat arg1 arg2

判断调用其他程序或批处理返回值(注意空格和括号和else位置)
if errorlevel 0 (
...成功
) else (
...失败
)
if not %errorlevel% == 0 ... 失败

call other.bat arg1 arg2 && ... 成功后执行

call other.bat arg1 arg2 || ... 失败后执行

退出
最好使用如下lable + goto方式
goto exit
:exit
也可以使用
exit exitcode 退出cmd解释器
exit /b exitcode 退出当前bat

创建目录
if not exist DIR mkdir DIR
复制目录
xcopy SRC DEST /s /e /y

遍历目录中的目录
for /d %%i in (DIR\*) do ( echo %%i )
遍历目录中的文件
for %%i in (DIR\*) do ( echo %%i )
递归遍历目录中的文件
for /r DIR %%i in (*) do ( echo %%i )
for /f "" %%i in ('dir /a:-d /b /s %1') do ( echo %%i )

%%~fi:表示获取该文件的绝对路径信息
%%~di:表示获取该文件所在的盘符
%%~pi:表示获取该文件的路径,不包含盘符的信息
%%~ni:表示获取该文件的文件名,不包含扩展名信息
%%~xi:表示获取该文件的扩展名
%%~ti:表示获取该文件的上次修改时间
%%~zi:表示获取该文件的大小
%%~nxi:表示获取该文件的文件名和扩展名,不包含盘符以及路径信息

逐个取值
for %%i in (aa bb cc) do (
echo %%i
)

判断字符串中是否含有
echo %1 |findstr "^abc" >nul
echo %errorlevel%

if “%PP:.svn=%” == “%PP%” echo not contain .svn

延迟环境变量扩展,在循环体中使用变量时要注意,如果不用延迟扩展,这个变量值是不会变的
setlocal EnableDelayedExpansion

for ... (
  call ...
  if !errorlevel! == 1 (
    echo !errorlevel!
  )
)

 使用bat文件启动cmd,并设置bat所在目录设置为当前目录
File: start_cmd_from_here.bat
----------------------------------------
cmd /k cd /d %~dp0

猜你喜欢

转载自www.cnblogs.com/lgc2003/p/12713491.html