最後更新: 2019-08-09
目錄
Comment
REM [Message]
:: [Message]
Add exe to PATH
SET PATH=%PATH%;C:\cygwin\bin
batch script set window size
MODE [width],[height]
i.e.
MODE 80,24
Variables
i.e.
@echo off & cls
set var=testing 1 2 3
echo The variable is "%var%"
pause > null
set
- set [<Variable>=[<String>]]
- set [/p] <Variable>=[<PromptString>]
- set /a <Variable>=<Expression>
/p Sets the value of Variable to a line of input entered by the user.
<PromptString>
Optional. Specifies a message to prompt the user for input.
This parameter is used with the /p command-line option.
/a Sets String to a numerical expression that is evaluated.
Colon in batch variable name
Variable Edit/Replace:
%variable:StrToFind=NewStr%
i.e.
:: Replace '1234' with 'Hello ' SET test=1234abcd echo %test:1234=Hello % echo %test%
Variables: extract part of a variable (substring):
%variable:~num_chars_to_skip%
%variable:~num_chars_to_skip,num_chars_to_keep%
* This can include negative numbers
SET DATE=%date% SET DAY=%DATE:~0,2% SET MONTH=%DATE:~3,2% SET YEAR=%DATE:~6,4% SET DATE_FRM=%YEAR%-%MONTH%-%DAY%
現在的日期及時間
%date%
03/26/2020 Thu
%time%
15:18:59.21
stdin 與 stderr
If you redirect the output to the NUL device using "dir file.xxx > nul",
you will still see the error message:
File Not Found
To redirect the error message to NUL, use the following command:
dir file.xxx 2> nul
Or, you can redirect the output to one place, and the errors to another.
dir file.xxx > output.msg 2> output.err
You can print the errors and standard output to a single file by using the "&1" command to redirect the output for STDERR to STDOUT and then sending the output from STDOUT to a file:
dir file.xxx 1> output.msg 2>&1
Parameter
parameters %0 to %9
- %0 is the program name as it was called,
- %1 is the first command line parameter,
- %2 is the second command line parameter,
test for the existence of a command line parameter
@ECHO OFF IF "%1"=="" ( ECHO "VSS" ) ELSE ( ECHO "BACKUP" )
Quotes
If the passed argument has quotes around it, %1 includes the quotes.
Where as, %~1 provides the argument value with quotes removed.
bat check file exists
@echo off IF EXIST filename. ( del filename. ) ELSE ( echo filename. missing. )
EXIT
EXIT [/B] [exitCode]
/B # When used in a batch script, this option will exit only the script (or subroutine) but not CMD.EXE
exitCode # Sets the %ERRORLEVEL% to a numeric number.
i.e.
C:\>echo %ERRORLEVEL%
9009
Windows batch assign output of a program to a variable
application arg0 arg1 > temp.txt
set /p VAR=<temp.txt
PAUSE
The most obvious way to pause a batch file is of course the PAUSE command.
This will stop execution of the batch file until someone presses "any key"
Sleep
TIMEOUT
"TIMEOUT" will delay execution of the next command by N seconds,
or until a key is pressed, whichever is shorter.
# press a key to continue ...
TIMEOUT /T 10
# press CTRL+C to quit ...
TIMEOUT /T 10 /NOBREAK
i.e.
@echo off echo %time% timeout 5 /nobreak > NUL echo %time%
另一個 Sleep 方案
# 假設 IP 192.168.0.253 沒有被設備使用, 以下 cmd 會在 60 秒內等對方回應
PING 192.168.0.253 -n 1 -w 60000 >NUL
FOR /L
Conditionally perform a command for a range of numbers.
Syntax
FOR /L %%parameter IN (start,step,end) DO command
Key
start : The first number
step : The amount by which to increment the sequence
end : The last number
%%parameter : A replaceable parameter
# Count from 1 up to 100
for /l %x in (1, 1, 5) do echo %x
* Use two %s if it's in a batch file
FOR Command
# echo Sun ~ Sat
FOR %G IN (Sun Mon Tue Wed Thur Fri Sat) DO echo %G
FOR /F
file-set is one or more file names.
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
Run batch files one by one
要 run 的每個script 前都要加 call
Example
run-all.bat
call C:\bak-jobs\b.bat
call C:\bak-jobs\a.bat
原因係 Backward Compatibility
In ancient dos versions it was not possible to recursively execute batch files.
Then the call command was introduced that called another cmd shell to execute the batch file and
returned execution back to the calling cmd shell when finished.
Call ALL bat in Folder
FOR %x IN (*.bat) DO call "%x"
Run batch files Simultaneously
Monitor.bat
start cmd.exe /C D:\batch1.bat
start cmd.exe /C D:\batch2.bat
start cmd.exe /C D:\batch3.bat
Remark
- /C Carries out the command specified by string and then terminates
- /K Carries out the command specified by string but remains
Multiple commands on a single line
ping 192.168.123.1 > null && echo "mount drive on server"
&& 與 &
& # separates commands on a line.
&& # runs the second command on the line when the first command comes back successfully, or with an errorlevel of 0.
|| # The opposite of &&.
Run cmd on exit
This is not possible.
CMD do not have any kind of event triggered command.
This includes events such as closing its window, moving its window, scrolling its window contents, and mouse clicks.
方案
Run a secondary cmd in silent mode that will always check the first cmd running with pid.
When the first not appear the secondary trigger the require event and run exit cmd to close itself.
ERRORLEVEL number
Specifies a true condition only if the previous program run by cmd.exe returned an exit code equal to or greater than Number.
其中一次 ping 成功, ERRORLEVEL 就會 0
echo %ERRORLEVEL%
SETLOCAL
EnableDelayedExpansion
cause variables within a batch file to be expanded at execution time rather than at parse time
SETLOCAL EnableDelayedExpansion
"for"的時候在迴圈中想要去改 set Variable 卻無法改變.
set var=0 for %%a in (1 1 1 1 1) do ( set /a var+=%%a echo %var% ) echo %var%
原因是 var 在parse的時候就會被提前展開, 所以在迴圈中 echo 出的值會是一開始parse時候的值
if ... else ...
EXIST
IF EXIST "temp.txt" ECHO found
IF NOT EXIST "temp.txt" ECHO not found
if ... else ...
IF EXIST "temp.txt" (
ECHO found
) ELSE (
ECHO not found
)
String Comparisons
if [not] <String1>==<String2> <Command> [else <Expression>]
CompareOp:
- EQU Equal to
- NEQ Not equal to
- LSS Less than
- LEQ Less than or equal to
- GTR Greater than
- GEQ Greater than or equal to
/i Forces string comparisons to ignore case.
Artimetic Comparisons
SET /A var=1
IF /i "%var%" EQU "1" ECHO equality with 1
Default Value
IF "%var%"=="" (SET var=default value)
ERRORLEVEL
if [not] ERRORLEVEL <Number> <Command> [else <Expression>]
IF "%ERRORLEVEL%" NEQ "0" ( ECHO execution failed )