Windows批处理文件有哪些不太为人所知,但很重要和有用的特性?
指南:
每个答案一个特征 给出特性的简短描述和示例,而不仅仅是文档链接 将答案限制在本地功能,即不需要额外的软件,如Windows资源包
澄清:这里我们指的是由cmd.exe处理的脚本,这是WinNT变体的默认值。
(请参见:Windows批处理文件:.bat vs .cmd?)
Windows批处理文件有哪些不太为人所知,但很重要和有用的特性?
指南:
每个答案一个特征 给出特性的简短描述和示例,而不仅仅是文档链接 将答案限制在本地功能,即不需要额外的软件,如Windows资源包
澄清:这里我们指的是由cmd.exe处理的脚本,这是WinNT变体的默认值。
(请参见:Windows批处理文件:.bat vs .cmd?)
当前回答
dos命令宏。
我已经很久没有参考过这一点了,但我仍然认为这是一个好主意,值得分享。
我们可以将批处理文件和doskey脚本合并到一个文件中。这可能看起来有点过于聪明,但它确实有效。
;= @echo off
;= rem Call DOSKEY and use this file as the macrofile
;= %SystemRoot%\system32\doskey /listsize=1000 /macrofile=%0%
;= rem In batch mode, jump to the end of the file
;= goto end
;= Doskey aliases
h=doskey /history
;= File listing enhancements
ls=dir /x $*
;= Directory navigation
up=cd ..
pd=pushd
;= :end
;= rem ******************************************************************
;= rem * EOF - Don't remove the following line. It clears out the ';'
;= rem * macro. Were using it because there is no support for comments
;= rem * in a DOSKEY macro file.
;= rem ******************************************************************
;=
它通过定义一个假的doskey宏';'来工作,当它被解释为批处理文件时,它会被优雅地(或无声地)忽略。
我缩短了这里列出的版本,如果你想要更多,请点击这里。
其他回答
我总是发现很难阅读每行用关键字标记的注释:
REM blah blah blah
易于阅读:
:: blah blah blah
FOR命令!虽然我讨厌写批处理文件,但我很感激它。
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
将解析myfile.txt中的每一行,忽略以分号开头的行,将每行的第2和第3个标记传递给for主体,标记由逗号和/或空格分隔。 注意for语句引用%i获取第二个令牌,引用%j获取第三个令牌,引用%k获取第三个令牌之后的所有剩余令牌。
你也可以用它来遍历目录、目录内容等等…
这里将介绍如何通过扫描给定目录来构建CLASSPATH。
setlocal ENABLEDELAYEDEXPANSION
if defined CLASSPATH (set CLASSPATH=%CLASSPATH%;.) else (set CLASSPATH=.)
FOR /R .\lib %%G IN (*.jar) DO set CLASSPATH=!CLASSPATH!;%%G
Echo The Classpath definition is %CLASSPATH%
适用于XP(或更好)。对于W2K,您需要使用两个BAT文件来实现相同的结果(请参阅在类路径定义中包含所有jar)。
在1.6版本中不需要它,因为你可以直接在CLASSPATH中指定通配符(例如-cp ".\lib*")。
要从文件的第一行开始设置一个环境变量,我使用以下命令:
rem a.txt contains one line: abc123
set /p DATA=<a.txt
echo data: %DATA%
这将输出:abc123
dos命令宏。
我已经很久没有参考过这一点了,但我仍然认为这是一个好主意,值得分享。
我们可以将批处理文件和doskey脚本合并到一个文件中。这可能看起来有点过于聪明,但它确实有效。
;= @echo off
;= rem Call DOSKEY and use this file as the macrofile
;= %SystemRoot%\system32\doskey /listsize=1000 /macrofile=%0%
;= rem In batch mode, jump to the end of the file
;= goto end
;= Doskey aliases
h=doskey /history
;= File listing enhancements
ls=dir /x $*
;= Directory navigation
up=cd ..
pd=pushd
;= :end
;= rem ******************************************************************
;= rem * EOF - Don't remove the following line. It clears out the ';'
;= rem * macro. Were using it because there is no support for comments
;= rem * in a DOSKEY macro file.
;= rem ******************************************************************
;=
它通过定义一个假的doskey宏';'来工作,当它被解释为批处理文件时,它会被优雅地(或无声地)忽略。
我缩短了这里列出的版本,如果你想要更多,请点击这里。