If you are a programmer from C/C++ or other advanced programming language, you might found that the Windows batch file programming is extremely madding.
Here is a list of the perplexing part of the Windows batch file programming that may make you mad.
The string substitute
To substitute a string, you should use
The !VAR! (delayed environment variable expansion) usually don't work for you, because the "delayed environment variable expansion" feature is not enabled by default. You will find this is really boring. There is 2 way to enable the "delayed environment variable expansion", so far as I know.
I prefer the former:Here is a list of the perplexing part of the Windows batch file programming that may make you mad.
Comments
You will find that the Windows batch files starts a comment line by "rem". That is boring! A simple way to start a comment is "::".
:: This is a comment line
:: This is another comment.
Echo a empty line
To echo a empty line, you might think the follow would work.
echobut it just report echo status. Actually you should use this.
echo.
The if...else...block
The right way to write a if...else...block is.if exist "a.txt" (Note, you must use "(" and ")" here.
echo deleting...
del a.txt
) else (
echo already done!
)
How to check if a directory is exist
This code
if exist "path\to\dir" (will print Yes when a directory or file named "dir" were exist at path "path\to". So you can use this to check a folder's existence. To do so append a "\NUL" at the of the path.
echo Yes
) else (
echo No
)
if exist "path\to\dir\NUL" (
echo Yes
) else (
echo No
)
The string substitute
To substitute a string, you should useset VAR=%VAR:str1=str2%This will replace all str1 in %VAR% with str2, and then assign the result to VAR.
The !VAR! doesn't work
The !VAR! (delayed environment variable expansion) usually don't work for you, because the "delayed environment variable expansion" feature is not enabled by default. You will find this is really boring. There is 2 way to enable the "delayed environment variable expansion", so far as I know.
- using /V:ON switch to invoke the cmd.exe
- add a DWORD registry key named DelayedExpansion under HKLM\Software\Microsoft\Command Processor (or HKCU), and set the key value to 1.
set TEST=any-stringThe if statement is checking if the "delayed environment variable expansion" if work or not. If no, just call the %COMSPEC% (cmd.exe) with /V:ON and execute this batch itself with the same command line arguments.
if not "!TEST!"=="%TEST%" (
%COMSPEC% /V:ON /C %~dpnx0 %*
goto :eof
)
:: normal process code here...
The multipurpose for command
To be updated!
No comments:
Post a Comment