如何在批处理中检查参数是否为空? [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我从批处理开始,我需要做一个简单的练习,但是我有一些问题。

在练习中,我需要用cmd引入3个参数,并检查只有3个,不多,不少。然后我需要检查每个参数,看看每个人是否等于一个字母,(%1应该是a%2 b%3 c)。

@echo off


if (%1=="") (goto end) else (goto c1)
:c1
if ("%2" =="") (goto error) else (goto c2)
:c2
if ("%3" =="") (goto error) else (goto c3)
:c3
if (%4=="") (goto c4) else (goto c4)
:c4

if ("%1"=="a") (goto p1) else (goto conditions) 
:p1
if ("%2"=="b") (goto p2) else (goto conditions) 
:p2
if ("%3"=="C") (goto end) else (goto conditions) 
goto end


:error
echo "Error"
goto fin


:conditions
echo "Error with parameters"

:end
batch-file
1个回答
2
投票

而是使用:

if "%~1" == "" (
 goto end
) else (
  goto c1
)

括号不是if语法的比较部分的一部分。虽然它们不会产生语法错误,但条件中的逻辑是错误的,因为它们将被视为比较字符串的一部分。

使用%~1删除参数周围的引号(如果有的话)并使用引号来处理参数中的空格。

在括号之前和之后放置空格,因为在某些情况下,如果不与命令分开,它们可能会出现语法错误。我个人更喜欢新行,因为它们提高了可读性。

最好从检查最后一个参数(在你的情况下为4)开始,好像一个被省略,cmd解析器将从1开始计数。

© www.soinside.com 2019 - 2024. All rights reserved.