3 回答

TA貢獻1784條經驗 獲得超9個贊
您可以使用:
IF "%~1" == "" GOTO MyLabel
去除外部引號。通常,與使用方括號相比,這是一種更可靠的方法,因為即使變量中有空格,該方法也將起作用。

TA貢獻1797條經驗 獲得超6個贊
最好的半解決方案之一是將其復制%1到變量中,然后使用延遲擴展(如delayExp)。對任何內容始終是安全的。
set "param1=%~1"
setlocal EnableDelayedExpansion
if "!param1!"=="" ( echo it is empty )
rem ... or use the DEFINED keyword now
if defined param1 echo There is something
這樣的好處是處理param1是絕對安全的。
而且param1的設置在很多情況下都可以使用,例如
test.bat hello"this is"a"test
test.bat you^&me
但是它會失敗,并帶有諸如
test.bat "&"^&
為了能夠獲得100%正確的存在答案,您可以使用此代碼塊,
它檢測是否%1為空,但是對于某些內容,它無法獲取內容。
這對于區分空值%1和帶的值也很有用""。
它使用CALL命令的能力而不會中止批處理文件而失敗。
@echo off
setlocal EnableDelayedExpansion
set "arg1="
call set "arg1=%%1"
if defined arg1 goto :arg_exists
set "arg1=#"
call set "arg1=%%1"
if "!arg1!" EQU "#" (
echo arg1 exists, but can't assigned to a variable
REM Try to fetch it
call set arg1=%%1
goto :arg_exists
)
echo arg1 is missing
exit /b
:arg_exists
echo arg1 exists, perhaps the content is '!arg1!'
添加回答
舉報