调试 Windows 命令行语法错误



我正在学习 Windows 命令行课程,但我的批处理文件收到一条我不理解的错误消息。我应该创建一个批处理文件,该文件接受参数并打印它们是否是环境变量。这是我到目前为止所拥有的:

::  Disable echoing of batch file commands to console.
@echo off
rem ********Begin Header******************
::  Author:     Megan
::  Date:   04/08/2018
::  File:   checkVars.bat
::  Descr:
::  This script determines if a given
::  set of arguments are defined
::  environmental variables.
rem ********End Header********************
::  Check to make sure at least one command
::  line argument has been given. If not,
::  display a usage message and exit the 
::  batch file. 
if "%1" == "" (
   echo Usage: %0 varname1 ...
   echo Determines if variable name is defined
   exit /b 1
)
:: determine if arguments %1 and greater
:: are environmental variables
:again
if not "%1" == "" (
   if defined %1 (
      echo %1 is a defined environment variable.
      echo.
   ) else (
      echo %1 is NOT a defined environment variable.
      echo.
   )
   shift /1
   goto again
) 

当我使用命令checkVars windir mydir prompt myvar运行批处理文件时,我得到以下输出:

windir is a defined environmental variable.
mydir is NOT a defined environmental variable.
prompt is a defined environmental variable.
myvar is NOT a defined environmental variable.
The syntax of the command is incorrect.

看起来我的代码正在额外运行一次。谁能帮我指出错误的方向?

看了你的代码后,我注意到你需要用引号括起来一些部分。导致语法错误的主要原因是if defined %1,其中%1需要变得"%1"。希望这解决了您的问题。

更正的代码:

::  Disable echoing of batch file commands to console.
@echo off
rem ********Begin Header******************
::  Author:     Megan
::  Date:   04/08/2018
::  File:   checkVars.bat
::  Descr:
::  This script determines if a given
::  set of arguments are defined
::  environmental variables.
rem ********End Header********************
::  Check to make sure at least one command
::  line argument has been given. If not,
::  display a usage message and exit the 
::  batch file. 
if "%1" == "" (
   echo Usage: %0 varname1 ...
   echo Determines if variable name is defined
)
:: determine if arguments %1 and greater
:: are environmental variables
:again
if not "%1" == "" (
   if defined "%1" (
      echo %1 is a defined environment variable.
      echo.
   ) else (
      echo %1 is NOT a defined environment variable.
      echo.
   )
   shift /1
   goto again
) 

最新更新