Summary of batch script usage

  • Batch (Batch), also known as batch script. As the name implies, batch processing is to process an object in batches, and it is usually considered as a simplified scripting language, which is used in DOS and Windows systems. Batch files have the extension bat (or cmd). Usually we specify the batch refers to the DOS batch script.
  • DOS batch processing is based on DOS commands, and is used to automatically execute DOS commands in batches to achieve specific operations. In more complicated situations, you need to use if, for, goto and other commands to control the running process of the program, just like high-level languages ​​​​such as C and Python. If more complex applications need to be implemented, it is necessary to use external programs, including external commands provided by the system itself and tools or software provided by third parties. Although the batch program runs in the command line environment, it can not only use the command line software, any program that can run under the current system can be run in a batch file.

1. Common commands

Commonly used commands can also be found in the article: link

  • folder management
    • cd displays the current directory name or changes the current directory.
    • md creates a directory.
    • rd deletes a directory.
    • dir Displays a list of files and subdirectories in a directory.
    • tree Graphically displays the folder structure of a drive or path.
    • path Displays or sets a search path for executable files.
    • xcopy copies files and directory trees.
  • file management
    • type Displays the contents of the text file.
    • copy Copies one or more files to another location.
    • del deletes one or several files.
    • move moves files and renames files and directories. (not in Windows XP Home Edition)
    • ren Renames a file.
    • replace replaces the file.
    • attrib Display or change file attributes.
    • find Search string.
    • fc compares two files or two sets of files and displays the differences between them
  • network command
    • ping for network connection testing, name resolution
    • ftp file transfer
    • net Network command set and user management
    • telnet remote login
    • ipconfig displays and modifies TCP/IP settings
    • msg send a message to the user
    • arp Display and modify the IP address-physical address mapping list of the LAN
  • System Management
    • at Schedules commands and programs to be run at specific dates and times
    • shutdown Immediate or scheduled shutdown or restart
    • tskill end process
    • taskkill to end the process (advanced than tskill, but there is no such command in WinXPHome version)
    • tasklist displays a list of processes (not in Windows XP Home Edition)
    • sc system service setting and control
    • reg registry console tool
    • powercfg controls the power settings on the system

2. Basic Grammar

Note that bat scripts are not case sensitive.

1. rem and::

:: is used to comment on the text, and the content will not be echoed after execution.
rem is used for text comments, and the content will be echoed after execution.

2. echo sum @

Putting the @ character before the command will disable the echo of the command, no matter whether echo is enabled or not.

  • Turn on the echo function:echo on
  • Turn off the echo function:echo off
  • output empty line: echo.or echo,or echo:or echo/etc.
  • Display the current echo status:echo
  • Output prompt information:echo 信息内容
  • Answer questions:echo 答复语|执行的操作
  • create a new file:echo 文件内容>文件名
  • What's new:echo 文件内容>>文件名
  • The horn sounds:echo ^g

3. pause

Pause the current program and output the following content to let us know where the program is running.
Show additional prompts:echo 其他提示语 & pause > nul

insert image description here

4. errorlevel

Obtain program return code: echo %errorlevel%
After each command is executed, you can use this command line format to view the return code. It is used to judge whether the command just executed is successful or not. The default value is 0, and errorlevel will be set to 1 if the general command execution fails.

5. title

Set the title of the cmd window, the syntax is as follows:

title 我的窗口

insert image description here

6. color

Set the foreground and background colors of the default console, the syntax is as follows:

color [前景色][背景色]

The color property is specified by two hexadecimal numbers - the first is the background color, the second the foreground color. Each number can be one of any of the following values.

value color value color
0 ⿊⾊ 8 gray
1 blue 9 light blue
2 green A light green
3 lake blue B light green
4 red C light red
5 purple D lavender
6 yellow E pale yellow
7 ⽩⾊ F bright white

Examples are as follows:
insert image description here

7. goto sum:

Jump execution commands can be realized through gotoand .:标号

@echo off
:start
set /a var+=1
echo %var%
if %var% leq 3 GOTO start
pause

8. find

Search for a string in a file, the syntax is as follows:

find [/v][/c][/n][/i][/off[line]] "字符串" [[drive:][path]filename[...]]
  • /v displays all lines that do not contain the specified string
  • /c show only the number of lines containing the string
  • /n show line number
  • /i Ignore case when searching for strings
  • /off[line] Do not skip files with offline attribute set
  • "string" specifies the string to search for
  • [drive:][path]filename specifies the file to search

9. start

The commands used to call external programs in batch processing have the following syntax:

start 外部程序 [参数]
  • This command will run the external program in a new process, and the original batch program will continue to execute
  • Executing and running an external program will wait for the completion of the external program before continuing to execute subsequent instructions.
    For example: start explorer d:\the D drive will be opened using a graphical interface.

10. assoc and ftype

assoc and ftype can realize file association, the syntax is as follows:

assoc .txt	::显示.txt代表的“文件类型”,结果显⽰.txt=txtfile
ftype		::显示所有的文件类型关联

assoc .txt=Word.Document.8  ::设置.txt文件未word类型的文档,可看到.txt文件图标已改变

11. pushd and popd

Mainly used to save and return to the initial directory, examples are as follows:

cd /d d:\mp4 	::更改当前⽬录为 d:\mp4
pushd c:\mp3 	::保存当前⽬录,并切换当前⽬录为 c:\mp3
popd 			::恢复当前⽬录为刚才保存的 d:\mp4

12. call

The CALL command can call another batch during the execution of a batch, and then continue to execute the original batch after the other batch is executed. The syntax is as follows:

call 指定批处理文件

13. if

Conditional judgment statement, the syntax is as follows:

if [not] errorlevel number command
if [not] str1==str2 command
if [not] exist filename command

3. Commonly used special symbols

1. @

Used before any command to turn off echoing for the current line.

2. %

%0 %1 %2 %3 %4 %5 %6 %7 %8 %9 %*为命令⾏传递给批处理的参数
%0 批处理⽂件本⾝,包括完整的路径和扩展名
%1 第⼀个参数
%9 第九个参数
%* 从第⼀个参数开始的所有参数

3. >

The standard input and output of DOS are usually carried out on standard equipment keyboards and monitors. Using redirection, the input and output can be easily redirected to disk files or other devices. in:

  • greater than >send command to file or device, such as printer>prn
  • double greater than >>appends the output of the command to the end of the file without deleting information already in the file
  • Less-than sign <Gets the input required for a command from a file instead of the keyboard
  • >&symbol redirects output from one default I/O stream (stdout, stdin, stderr) to another default I/O stream

4. >>

>>It is >somewhat similar to , but the difference is >>that is passed and appended at the end of the file, but >overwritten.

Four, common usage

1. Set temporary environment variables

The environment variable set in the command line mode is a temporary environment variable, which is only valid for the current CMD command window, and does not affect the environment variables in other windows, let alone the permanent environment variables. To set a permanent environment Variables need to be modified through graphics operations.

CMD

set path=%path%;C:\test  ::在原有环境变量的基础上追加环境变量

PowerShell

$env:path+="C:\test"

2. Start CMD to execute the command

start cmd /k    ::启动一个CMD且不关闭CMD
start cmd /c    ::启动一个CMD且关闭CMD
start cmd /k  "命令1 & 命令2 & 命令3"     ::无论前面命令是否成功, 后面都会执行
start cmd /k "命令1 && 命令2 && 命令3 "   ::仅当前面命令成功时, 才执行后面,一般用这个
start cmd /k "命令1 || 命令2 || 命令3"    ::仅当前面命令失败时. 才执行后面

If you need to execute the specified script file, please use callthe command, the example is as follows:

call test.bat

3. Open the environment variable window

rundll32 sysdm.cpl,EditEnvironmentVariables

4. Get user input and display

@echo off

set /p user_input=请输入内容:
echo 你输入的内容是:%user_input%

References:

https://www.jb51.net/article/250331.htm
http://www.taodudu.cc/news/show-3034558.html
https://www.w3cschool.cn/dosmlxxsc1/wvqyr9.html
https://www.runoob.com/linux/linux-shell-variable.html
https://www.hxstrive.com/subject/windows_bat.htm?id=36
https://cloud.tencent.com/developer/article/2118950
https://www.yiibai.com/batch_script/
https://zhuanlan.zhihu.com/p/415626343
http://t.csdn.cn/hJaPh
http://t.csdn.cn/3R7Be
http://t.csdn.cn/zFfr5
http://t.csdn.cn/JmcoH
http://t.csdn.cn/ui048

Guess you like

Origin blog.csdn.net/hfy1237/article/details/130123285