博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
几个批处理命令
阅读量:2190 次
发布时间:2019-05-02

本文共 12682 字,大约阅读时间需要 42 分钟。

1 set 命令:

利用set /? 可以查看set命令的详细使用

set命令设置自定义变量显示、设置或删除 cmd.exe 环境变量。SET [variable=[string]]variable指定环境变量名。

set 如果后面不加参数,则显示系统所有的环境变量

set + 字母,可以显示以这些字母开头的环境变量。

C:\Documents and Settings\Administrator>set cl
classpath=C:\STAF\samples\demo\STAFDemo.jar;C:\STAF\bin\JSTAF.jar;C:\jdepend-2.9
\jdepend-2.9\lib\jdepend-2.9.jar;C:\Program Files\IBM\Java60\bin;C:\Program File
s\IBM\Java142\lib.

CLIENTNAME=Console

set其他的用法如 SET /A expression,SET /P variable=[promptString]

(1) 定义普通变量:

 set Release=df

 set Product=qa
 set ExcelPath=c:\Projects

(2)让变量支持数学计算使用/A

set /a retry_num=retry_num+1

(3) 支持用户交互的/P

set /p str="please enter"

type %str%

(4) 字符串截取

**********************************************

截取功能统一语法格式为:%a:~[m[,n]]%
**********************************************
方括号表示可选,%为变量标识符,a为变量名,不可少,冒号用于分隔变量名和说明部分,符号~可以简单理解为“偏移”即可,m为偏移量(缺省为0),n为截取长度(缺省为全部)

%PATH:~10,5%

set a=bbs.seu.cn

set var=%a:~2,-3%
echo %var%

这是表示截取从第二个字符开始,到倒数第三个字符串结束的字符。

看解释:

    %PATH:~10,5%
would expand the PATH environment variable, and then use only the 5characters that begin at the 11th (offset 10) character of the expanded result.  If the length is not specified, then it defaults to the remainder of the variable value.  If either number (offset or length) is negative, then the number used is the length of the environment variable value added to the offset or length specified.
    %PATH:~-10%
would extract the last 10 characters of the PATH variable.

2 echo 和type的区别:

type用来显示文件内容,echo相当于print

C:\Documents and Settings\Administrator\Desktop>type /?
Displays the contents of a text file or files.
TYPE [drive:][path]filename
C:\Documents and Settings\Administrator\Desktop>echo /?
Displays messages, or turns command-echoing on or off.
  ECHO [ON | OFF]
  ECHO [message]

Type ECHO without parameters to display the current echo setting.

3 call:调用其他的程序或者批处理脚本

从批处理程序调用另一个批处理程序。
CALL [drive:][path]filename [batch-parameters]
   batch-parameters    指定批处理程序所需的命令行信息。
如果命令扩展名被启用,CALL 会如下改变:
CALL 命令现在将卷标当作 CALL 的目标接受。语法是:
     CALL:label arguments
一个新的批文件上下文由指定的参数所创建,控制在卷标被指定
后传递到语句。您必须通过达到批脚本文件末两次来 "exit" 两次。
第一次读到文件末时,控制会回到 CALL 语句的紧后面。第二次
会退出批脚本。键入 GOTO /?,参看 GOTO   : EOF   扩展名的描述,

。。。。。。

4@

它的作用是让执行窗口中不显示它后面这一行的命令本身,通俗一点说,行首有了它的话,这一行的命令就不显示了。

如echo off

@echo off

将只会打印一个echo off

5 echo on/off

关闭回显本身。如果是echo on,不仅仅会显示命令本身还会显示运行结果。 否则设置为off的话只显示执行结果。

@echo on
set a=bbs.seu.cn
set var=%a:~2,-3%
echo %var%
pause

6 批处理注释:: 和rem

7 del命令:删除文件

如del /q %ExcelPath%\*.*

C:\Documents and Settings\Administrator>del /?

Deletes one or more files.
DEL [/P] [/F] [/S] [/Q] [/A[[:]attributes]] names
ERASE [/P] [/F] [/S] [/Q] [/A[[:]attributes]] names
  names         Specifies a list of one or more files or directories.
                Wildcards may be used to delete multiple files. If a
                directory is specified, all files within the directory
                will be deleted.
  /P            Prompts for confirmation before deleting each file.
  /F            Force deleting of read-only files.
  /S            Delete specified files from all subdirectories.
  /Q            Quiet mode, do not ask if ok to delete on global wildcard
  /A            Selects files to delete based on attributes
  attributes    R  Read-only files            S  System files
                H  Hidden files               A  Files ready for archiving
                -  Prefix meaning not
If Command Extensions are enabled DEL and ERASE change as follows:
The display semantics of the /S switch are reversed in that it shows
you only the files that are deleted, not the ones it could not find.
8: 定义标签 :LabelName

9()分隔符

使用它包括多条DOS命令,有点类似于c或者c++中的{},起包含语句块的作用!

10 if 结构:

if的三种结构

1:IF [NOT] exist filename command--判断文件存在

@echo off

if exist c:\defect.csv type c:\defect.csv
if not exist c:\\defect.csv echo "hello">c:defect.csv

2:IF [NOT] ERRORLEVEL number command--判断执行结果

if errorlevel 1 goto for

3:IF [NOT] string1==string2 command

@echo off

set /p %%a="please enter password"
if %%a=="password" (goto test) else goto error
:test
echo "correct"
:error
echo "error password"
常用比较操作符:

== - 等于  EQU - 等于  NEQ - 不等于  LSS - 小于  LEQ - 小于或等于  GTR - 大于  GEQ - 大于或等于  选择开关/i则不区分字符串大小写;选择not项,则对判断结果进行逻辑非。

附:

C:\Documents and Settings\Administrator>if /?

Performs conditional processing in batch programs.
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command

  NOT                Specifies that Windows XP should carry out  the command only if the condition is false.

  ERRORLEVEL  number Specifies a true condition if the last program run returned an exit code equal to or greater than the numbe  specified.

  string1==string2  Specifies a true condition if the specified text strings match.
  EXIST filename    Specifies a true condition if the specified filename  exists.
  command           Specifies the command to carry out if the condition is met.  Command can be followed by ELSE command which will execute the command after the ELSE keyword if the specified condition is FALSE
The ELSE clause must occur on the same line as the command after the IF.  For example:
    IF EXIST filename. (
        del filename.
    ) ELSE (
        echo filename. missing.
    )
The following would NOT work because the del command needs to be terminated by a newline:
    IF EXIST filename. del filename. ELSE echo filename. missing
Nor would the following work, since the ELSE command must be on the same lin as the end of the IF command:
    IF EXIST filename. del filename.
    ELSE echo filename. missing
The following would work if you want it all on one line:
    IF EXIST filename. (del filename.) ELSE echo filename. missing
If Command Extensions are enabled IF changes as follows:
    IF [/I] string1 compare-op string2 command
    IF CMDEXTVERSION number command
    IF DEFINED variable command
where compare-op may be one of:
    EQU - equal
    NEQ - not equal
    LSS - less than
    LEQ - less than or equal
    GTR - greater than
    GEQ - greater than or equal
and the /I switch, if specified, says to do case insensitive string compares.  The /I switch can also be used on the string1==string2 form of IF.  These comparisons are generic, in that if both string1 and string2 are both comprised of all numeric digits, then the strings are converted to numbers and a numeric comparison is performed.
The CMDEXTVERSION conditional works just like ERRORLEVEL, except it is comparing against an internal version number associated with the Command Extensions.  The first version is 1.  It will be incremented by one when significant enhancements are added to the Command Extensions. CMDEXTVERSION conditional is never true when Command Extensions are disabled.
The DEFINED conditional works just like EXISTS except it takes an environment variable name and returns true if the environment variable is defined.
%ERRORLEVEL% will expand into a string representation of the current value of ERRORLEVEL, provided that there is not already an environment variable with the name ERRORLEVEL, in which case you will get its value instead.  After running a program, the following illustrates ERRORLEVEL use:
    goto answer%ERRORLEVEL%
    :answer0
    echo Program had return code 0
    :answer1
    echo Program had return code 1
You can also using the numerical comparisons above:
    IF %ERRORLEVEL% LEQ 1 goto okay
%CMDCMDLINE% will expand into the original command line passed to CMD.EXE prior to any processing by CMD.EXE, provided that there is not already an environment variable with the name CMDCMDLINE, in which case you will get its value instead.
%CMDEXTVERSION% will expand into a string representation of the current value of CMDEXTVERSION, provided that there is not already an environment variable with the name CMDEXTVERSION, in which case you will get its value instead.

11 FOR循环:

11.无开关  

无开关的for语句能够对设定的范围内进行循环,是最基本的for循环语句。其命令格式为:  FOR %%variable IN (set) DO command

FOR %variable IN (set) DO command [command-parameters]
  %variable  Specifies a single letter replaceable parameter.
  (set)      Specifies a set of one or more files.  Wildcards may be used.
  command    Specifies the command to carry out for each file.
  command-parameters
             Specifies parameters or switches for the specified command.

@echo off

  for %%i in (a,"b c",d) do echo %%i
  pause>nul

2:FOR /L %%variable IN (start,step,end) DO command  其中,start为开始计数的初始值,step为每次递增的值,end为结束值。当end小于start时,step需要设置为负数。

FOR /L %variable IN (start,step,end) DO command [command-parameters]

    The set is a sequence of numbers from start to end, by step amount.
    So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would
    generate the sequence (5 4 3 2 1)

@echo off

for /l %%i in (1,2,10) do echo %%i
pause 

输出结果:

1

3
5
7
9
Press any key to continue . . .

3开关/D或/R  含开关/D或/R的for语句是与目录或文件有关的命令,一般情况下很少使用。(没用过,抄得)

含开关/R的命令有时候被用于通过遍历文件夹来查找某一个文件或文件夹,故而列举此例。  含开关/R的for语句举例(文件夹遍历):  

@echo off

  setlocal enabledelayedexpansion
  FOR /R d: %%i IN (.) DO (
  set dd=%%i
  set "dd=!dd:~0,-1!"
  echo !dd!
  )
  pause
  exit 

4FOR /F ["options"] %%variable IN (set) DO command

  @echo off

  for /f "tokens=1,3,5 delims=," %%a in ("1,2,10,2,5") do echo a=%%a b=%%b c=%%c
  pause
delims是以,为分割,tokens=1,3,5表示将循环中第一,三,五个变量赋值给a b c

FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]

FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
    or, if usebackq option present:
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]
    filenameset is one or more file names.  Each file is opened, read
    and processed before going on to the next file in filenameset.
    Processing consists of reading in the file, breaking it up into
    individual lines of text and then parsing each line into zero or
    more tokens.  The body of the for loop is then called with the
    variable value(s) set to the found token string(s).  By default, /F
    passes the first blank separated token from each line of each file.
    Blank lines are skipped.  You can override the default parsing
    behavior by specifying the optional "options" parameter.  This
    is a quoted string which contains one or more keywords to specify
    different parsing options.  The keywords are:
        eol=c           - specifies an end of line comment character
                          (just one)
        skip=n          - specifies the number of lines to skip at the
                          beginning of the file.
        delims=xxx      - specifies a delimiter set.  This replaces the
                          default delimiter set of space and tab.
        tokens=x,y,m-n  - specifies which tokens from each line are to
                          be passed to the for body for each iteration.
                          This will cause additional variable names to
                          be allocated.  The m-n form is a range,
                          specifying the mth through the nth tokens.  If
                          the last character in the tokens= string is an
                          asterisk, then an additional variable is
                          allocated and receives the remaining text on
                          the line after the last token parsed.
        usebackq        - specifies that the new semantics are in force,
                          where a back quoted string is executed as a
                          command and a single quoted string is a
                          literal string command and allows the use of
                          double quotes to quote file names in
                          filenameset.
    Some examples might help:
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
    would parse each line in myfile.txt, ignoring lines that begin with
    a semicolon, passing the 2nd and 3rd token from each line to the for
    body, with tokens delimited by commas and/or spaces.  Notice the for
    body statements reference %i to get the 2nd token, %j to get the
    3rd token, and %k to get all remaining tokens after the 3rd.  For
    file names that contain spaces, you need to quote the filenames with
    double quotes.  In order to use double quotes in this manner, you also
    need to use the usebackq option, otherwise the double quotes will be
    interpreted as defining a literal string to parse.
    %i is explicitly declared in the for statement and the %j and %k
    are implicitly declared via the tokens= option.  You can specify up
    to 26 tokens via the tokens= line, provided it does not cause an
    attempt to declare a variable higher than the letter 'z' or 'Z'.
    Remember, FOR variables are single-letter, case sensitive, global,
    and you can't have more than 52 total active at any one time.
    You can also use the FOR /F parsing logic on an immediate string, by
    making the filenameset between the parenthesis a quoted string,
    using single quote characters.  It will be treated as a single line
    of input from a file and parsed.
    Finally, you can use the FOR /F command to parse the output of a
    command.  You do this by making the filenameset between the
    parenthesis a back quoted string.  It will be treated as a command
    line, which is passed to a child CMD.EXE and the output is captured
    into memory and parsed as if it was a file.  So the following
    example:
      FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i
    would enumerate the environment variable names in the current
    environment.
12 转义字符:

  将特殊符号转化为一般符号,即剥离特殊符号的特殊地位。特殊符号指:| & > <, echo aaaa^>a.txt

转载地址:http://jpfub.baihongyu.com/

你可能感兴趣的文章
分布式系统理论基础1: 一致性、2PC和3PC
查看>>
分布式系统理论基础2 :CAP
查看>>
分布式系统理论基础3: 时间、时钟和事件顺序
查看>>
分布式系统理论基础4:Paxos
查看>>
分布式系统理论基础5:选举、多数派和租约
查看>>
分布式系统理论基础6:Raft、Zab
查看>>
分布式系统理论进阶7:Paxos变种和优化
查看>>
分布式系统理论基础8:zookeeper分布式协调服务
查看>>
搞懂分布式技术1:分布式系统的一些基本概念
查看>>
搞懂分布式技术2:分布式一致性协议与Paxos,Raft算法
查看>>
搞懂分布式技术3:初探分布式协调服务zookeeper
查看>>
搞懂分布式技术4:ZAB协议概述与选主流程详解
查看>>
搞懂分布式技术5:Zookeeper的配置与集群管理实战
查看>>
搞懂分布式技术6:Zookeeper典型应用场景及实践
查看>>
搞懂分布式技术10:LVS实现负载均衡的原理与实践
查看>>
搞懂分布式技术11:分布式session解决方案与一致性hash
查看>>
搞懂分布式技术12:分布式ID生成方案
查看>>
搞懂分布式技术13:缓存的那些事
查看>>
搞懂分布式技术14:Spring Boot使用注解集成Redis缓存
查看>>
搞懂分布式技术15:缓存更新的套路
查看>>