首页  编辑  

批处理如何正确判断参数是否为空

Tags: /计算机文档/脚本,批处理/   Date Created:
IF NOT %1 GOTO MyLabel // This is invalid syntax
IF "%1" == "" GOTO MyLabel // Works unless %1 has double quotes which fatally kills bat execution
IF %1 == GOTO MyLabel // Gives an unexpected GOTO error.

批处理中判断参数为空,一般做法是:
if "%1"=="" (
)
但这种做法有个缺点,如果参数1是以引号括起来的,比如长文件名,就会失败了出现错误。

正确的做法是:
if "%~1" == "" (
)

例如upload.bat:
@echo off

if "%~2" == "" (
  echo usage:
  echo    %~n0 [serverurl] [filename]
  goto end
)

curl -F "file=@%~2" %1

:end