【问题标题】:Debugging Windows Command Line Syntax Error调试 Windows 命令行语法错误
【发布时间】:2018-04-09 03:08:42
【问题描述】:

我正在学习 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.

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

【问题讨论】:

    标签: batch-file command-line syntax-error


    【解决方案1】:

    查看您的代码后,我注意到您需要用引号将某些部分括起来。导致语法错误的主要原因是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
    ) 
    

    【讨论】:

      猜你喜欢
      • 2017-07-16
      • 2017-05-22
      • 2021-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多