如何在 .bat 檔案中設定預設參數?

如何在 .bat 檔案中設定預設參數?

我有這樣的 .bat 程式碼。例如:

@ECHO OFF


setlocal EnableDelayedExpansion
call :setESC

set arg1=%1
set "noArgs=true"
for %%a in (%*) do (
    if not %%a == "" (
        :: if it is not empty arguments.
        set "noArgs=false"
    )
)

if "%noArgs%" == "true" (
    if "%arg1%" == "" (
        :: it is empty args AND argument1 (/arg) is empty
        :: set default argument here. <-----------
        set "%%1=build"
    )
)

:: for debugging.
echo all args: %* :end.

:: run external command (gulp).
gulp --cwd "/my/project" %*

吞嚥蝙蝠

從 CLI 中,如果我輸入命令,gulpbat build它將被調用到gulp build.但如果我打電話gulpbat,就會有回應任務從未定義:預設

我想新增預設任務(build如果命令列中缺少該任務並將自動使用)%*

我已經嘗試過這些但失敗了。

set "%1=build" :: error: The syntax of the command is incorrect.
set "%~1=build" :: error: The syntax of the command is incorrect.
set "%%1=build" :: not working in %*

答案1

@echo off && setlocal EnableDelayedExpansion 

:: // call :setESC // :label |or| :function not exist in your code! //

if "%~1" == "build" (
     set "_arg1=build"
    )else if not "%~1" == "" (
     set "_arg1=%~1" && for %%Z in (%*)do set "_args_=!_args_!"%%~Z" "
    )else set "_args_default=/define /your /defaults /args /here"

:: for debugging.
echo\ all args: !_args_! :end

:: run external command (gulp).
if defined _args_ (
     gulp --cwd "/my/project" !_args_!
    )else if defined _arg1 (
     gulp --cwd "/my/project" !_arg1!
    )else gulp --cwd "/my/project" !_args_default!

endlocal

相關內容