在.bat文件中,如果这些文件夹之间有任何差异,我需要比较2个文件夹并退出.bat文件。windows .bat文件。如何比较2个文件夹并生成比较结果的返回码?
不幸的是,comp
和windiff
没有提供不同结果比较的显式返回码。有没有其他方法来处理comp
或windiff
的结果来实现上述逻辑?
在.bat文件中,如果这些文件夹之间有任何差异,我需要比较2个文件夹并退出.bat文件。windows .bat文件。如何比较2个文件夹并生成比较结果的返回码?
不幸的是,comp
和windiff
没有提供不同结果比较的显式返回码。有没有其他方法来处理comp
或windiff
的结果来实现上述逻辑?
comp
如果文件(集合)不同,则将errorlevel设置为1。 你可以用if errorlevel
测试(help if
阅读细节),或者你可以(在你的情况comp folderA folderB || exit /b
)使用
cmd && cmd_to_execute_if_successful
cmd || cmd_to_execute_if_unsuccessful
实际上,这两个comp
和fc
会返回一个错误级别,它们都只是有点吵。所以最好将它们的输出输入nul
。
:: Comp asks a Y/N question via `stderr` (stream2)
:: Comp prints the differences between files on `stdout` (stream1)
:: So we answer the question, and divert both streams to `nul`
echo n | comp dir1 dir2 > nul 2>&1
if %errorlevel%==0 (
echo The directories are the same.
) else (
echo The directories are different.
)
:: FC simply outputs the differences between the files via `stdout`
:: So it's only nessicary to redirect `stdout` (stream1) to nul
fc dir1\* dir2\* > nul
if %errorlevel%==0 (
echo The directories are the same.
) else (
echo The directories are different.
)
或者,如WMZ指出...
echo n | comp dir1 dir2 > nul 2>&1 && cmd_to_execute_if_successful
和
fc dir1\* dir2\* > nul || cmd_to_execute_if_unsuccessful
虽然,恕我直言,即编码是如此嘈杂这是一个有点难以阅读
注意:FC
做二进制比较,通常不是问题,b您可以通过添加/L
开关指定ASCII文本。 (fc /l dir1\*.txt dir2\*.txt
)
还记得别混淆NUL
和NULL
,它们是不一样的。
谢谢,wmz。我感到很尴尬,我没有找到有关返回代码的信息) –
实际上,上面的例子不会与'comp'一起工作,因为在比较文件后,但在退出之前,它会询问'Compare more files(Y/N)? '并等待回应。我通常这样称呼它:'echo n | comp filea fileb'。 –
@JamesK为了简洁和作为读者的小练习而放弃它,但是,没有用户交互的情况下运行它,您需要提供如您所示的“确认”(对于不同的语言版本,这可能会有所不同方式) – wmz