我需要測試是否設置了變量。我已經嘗試了幾種技術,但他們忽視了,只要%1用雙引號包圍時,如果%1是"c:\some path with spaces"。
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語法類型。因此,我沒有找到一種方法。使用 IF /?可以查看使用說明
IF [NOT] ERRORLEVEL number command //常用於錯誤號的比較,需要配合 EQU-等於; NEQ-不等於; LSS-小於; LEQ-小於或等於; GTR-大於; GEQ-大於或等於
IF [NOT] string1==string2 command //常用於字符串的比較,常配合/I參數強制字符串比較
IF [NOT] EXIST filename command //常用於判斷文件,例如參數傳入的是文件或路徑
------------------------------------------------
牧羊人nacy
使用方括號代替引號:
IF [%1] == [] GOTO MyLabel
括號不安全:只能使用方括號。
------------------------------------------------
千萬里不及你
您可以使用:
IF "%~1" == "" GOTO MyLabel
去除外部引號。通常,與使用方括號相比,這是一種更可靠的方法,因為即使變量中有空格,該方法也將起作用。
------------------------------------------------
FFIVE
最好的半解決方案之一是將其復制%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!'
出處:https://www.imooc.com/wenda/detail/606826
bat %n 判斷傳入的參數值和使用注意
if "%1" == "" echo empty 1
if exist "%1" echo 1path exist
注意:要加上雙引號"",不然如果傳入的參數是空的話,會導致bat閃退,因為如果是空,而沒有雙引號,那么就變成 if == "" echo empty 1,這是語法錯誤,如果有雙引號,那么就是 if "" == "" echo empty 1
