1

我不知道这个批处理文件有什么问题:

@ECHO OFF
SET images=./images/
SET cdr=%CD%
SET result=noval

CD %images%
SET images=
:: Density
SET dpi=300

:: Process SVG
FOR %%x IN (%images%*.svg) DO (
  CALL:testFun %%~nx result
  echo res "%result%"
  IF [%result%]==[process] (
    ECHO Converting %%x
    inkscape -d %dpi% -A %images%%%~nx.pdf %images%%%x
  ) ELSE ( ECHO - Skiping %%x, file is uptodate.)
)

:: Process BMP, JPG, PNG, and TIFF
FOR %%x IN (%images%*.jpg,%images%*.bmp,%images%*.png,%images%*.tiff) DO (
  CALL:testFun %%~nx result
  echo res "%result%"
  IF [%result%]==[process] (
    ECHO Converting %%x
    inkscape -d %dpi% -A %images%%%~nx.pdf %images%%%x 
  ) ELSE ( ECHO - Skiping %%x, file is uptodate.)
)



:: Process EPS
FOR %%x IN (%images%*.eps) DO (
  CALL :testFun %%~nx result
  echo res "%result%"
  IF [%result%]==[process] (
    ECHO Converting %%x
    epstopdf --outfile=%images%%%~nx.pdf %images%%%x
  ) ELSE ( ECHO - Skiping %%x, file is uptodate.)
)

CD %cdr%
ECHO.&PAUSE&GOTO:EOF

::Functions

:testFun
SET "file=%1"
FOR /F %%f IN ('dir /Od /B "%file%.*"') DO (SET newest=%%~xf)
echo * Newest file for %file%: %newest%
IF [%newest%]==[.pdf] (echo noprocessing
GOTO :noprocess) ELSE (echo processing
GOTO :process)
:noprocess
SET result=noprocess
GOTO :endfun
:process
SET result=process
:endfun
GOTO:EOF

这个想法是它应该处理目录中的不同图像,只有当图像(源)比生成的 PDF(输出)新时。

但是,有几个问题我不知道为什么会发生。

  • 首先,第一个循环一直使用result和 print的值noval,看起来它正在跳过函数调用。但是,相同的调用方式适用于第二个和第三个循环。

  • 其次,在其他循环中(没有出现第一个问题)result,在函数内部更改的 的值不存在。好像范围不同。但是,我将它用作全局变量,对吗?set local我使用变量作为参考来测试这个版本,但没有任何效果。

我在这里做错了什么或错过了什么?

4

1 回答 1

3

代码按应有的方式运行。您不知道的是在解析命令cmd时会扩展环境变量。在这种情况下,命令可以是包含块的完整命令。因此,在解析它之后,其中没有任何变量,只有文本。这意味着如果您更改块中的变量并同一块中使用它,您将看不到更改。for

要解决此问题,您可以使用延迟扩展,以确保变量在运行单行之前直接扩展(即使在块内),从而缓解此问题。在批处理文件的顶部添加以下内容:

setlocal enabledelayedexpansion

然后使用!result!而不是%result%访问变量的值。

于 2012-06-12T05:18:05.760 回答