批处理文件中的多个if语句

时间:2014-09-18 00:41:17

标签: batch-file gis dos

我必须提示用户输入文件名,然后检查该名称是否有三种必要的文件类型(.shp,.shx,.dbf),并检查可选的第四种(.prj)

 @echo off


set /p basename = Enter a file name: 

if exist %basename%.shp (
    if exist %basename%.shx (
        if exist %basename%.dbf (
            if exist %basename%.prj (
            echo %basename% is a complete shapefile.
            ) else ( echo %basname% is an acceptable shapefile.)
            )
            )
            ) else ( echo shapefile is incomplete)

原谅我的垃圾语法/格式,但我传入的所有内容都返回“shapefile不完整”。

1 个答案:

答案 0 :(得分:2)

你有一些问题。

1)定义变量时空间很重要。您的SET / P语句创建了一个名为“basename”的变量,末尾有一个尾随空格。但是你的IF语句使用的是名称中没有空格的变量。

2)如果外部IF为FALSE,则仅触发ELSE子句。如果.shp文件存在,但缺少其他所需文件之一,则应该没有输出。

3)你应该在IF语句中加上全名的引号,以防名称中有空格或毒药字符。

获得正确逻辑的最简单方法是使用临时变量来记录是否缺少其中一个文件。

我不会使用一堆单独的IF语句。相反,我会使用FOR循环来缩短和简化代码。

@echo of
setlocal
set /p "basename=Enter a file name: "
set "missing="
for %%X in (shp shx dbf) if not exist "%basename%.%%X" set missing=1
if defined missing (
  echo shapefile is incomplete
) else if exist "%basename%.prj" (
  echo "%basename%" is a complete shapefile
) else echo "%basename%" is an acceptable shapefile
相关问题