Gradle 9.8 常用 CLI 命令详解

Gradle 9.8 CLI 命令详解:build/test/run/clean、tasks/projects/properties、dependencies/dependencyInsight、init/wrapper、Daemon 生命周期与 --offline/-x/--refresh-dependencies 等标志,全部实测回显。

GradleGradle构建工具2026/10/20

Gradle 9.8 常用 CLI 命令详解

目标:系统梳理 gradle 命令行工具的任务命令与全局标志,逐条给出实测回显——覆盖构建主链(build/test/run/clean)、任务发现(tasks/projects/properties/help)、依赖分析(dependencies/dependencyInsight)、工程生成(init/wrapper)、Daemon 生命周期(--status/--stop)与常用标志(--offline/-x/--refresh-dependencies/--parallel 等)。全部命令在 Ubuntu 22.04 + Gradle 9.8.2 + OpenJDK 17 环境实测通过。

一、环境信息

  • 操作系统:Ubuntu 22.04.4 LTS(x86_64,内核 6.8.0-138-generic)
  • Gradle:9.8.2(官方发行包安装于 /opt/gradle-9.8.2,软链 /opt/gradle,安装过程见 《Ubuntu 22.04 安装 Gradle 9.8 指南》)
  • JDK:OpenJDK 17.0.20.1(运行 Gradle);Temurin 21.0.12.1_1(工具链,Gradle 自动下载于 ~/.gradle/jdks/)
  • 实验工程:/opt/demo-multi(多模块:根 + lib 库模块 + app 应用模块,Kotlin DSL;依赖含 commons-math3 3.6.1、guava 33.5.0-jre、junit-jupiter 6.0.1)
  • 工程已开启:org.gradle.caching=true、org.gradle.configuration-cache=true(配置详解见 《Gradle 9.8 配置参数详解》)

二、工具概览

gradle 命令的通用结构为:

gradle [task-name ...] [options...]

即「任务名列表 + 全局标志」两部分,任务可以写多个(一次构建跑多任务),标志全部以 -- 开头(多数有单字母缩写)。对多模块工程,任务可带模块前缀精确限定(如 :app:build 只构建 app 模块),不带前缀的 build 会在所有模块执行同名任务。

💡 技术拓展:与 Maven 命令形态对比——Maven 是「生命周期阶段」(mvn package 固定绑定到生命周期),Gradle 是「任务名」(gradle build 调用任务图中名为 build 的任务及其依赖)。因此 Gradle 可以直接执行任意粒度任务(gradle :app:jar、gradle javadoc),Maven 则需借助插件目标(mvn javadoc:javadoc)。本平台 Maven 命令篇见 《Apache Maven 3.10.0 常用 CLI 命令与工具详解》。

执行模型:gradle 命令先启动一个轻量客户端进程,实际构建由常驻 Gradle Daemon(后台 JVM)执行;Daemon 复用是二次构建秒级完成的前提(首次命令会打印 Starting a Gradle Daemon...,实测回显见 4.1 节)。

三、前置条件

  1. 已完成 Gradle 9.8.2 安装并 source /etc/profile.d/gradle.sh(或新开登录 shell),gradle --version 可正常输出(回显见 4.1 节)。

  2. 准备本文使用的实验工程(与安装篇一致的 init 命令,参数化生成):

    mkdir -p /opt/demo-multi && cd /opt/demo-multi
    gradle init --type java-library --dsl kotlin --test-framework junit-jupiter --package com.example.multi --project-name demo-multi --no-split-project
    

    生成后把 settings.gradle.kts 调整为双模块并追加一个自定义任务(app/build.gradle.kts 末尾):

    tasks.register("hello") {
        val projectName = project.name
        doLast {
            println("Hello from custom task, project = $projectName")
        }
    }
    
  3. 验证工程可构建:gradle build 输出 BUILD SUCCESSFUL 即就绪。

四、各工具详解

4.1 版本与 Daemon 生命周期:--version / --status / --stop

gradle --version:打印版本与运行环境(Daemon 排障第一步),实测回显:

------------------------------------------------------------
Gradle 9.8.2
------------------------------------------------------------

Build time:    2026-10-19 16:29:26 UTC
Revision:      8de7bcf76e785507ad92f0741ab9235a430c95e6

Kotlin:        2.4.10
Groovy:        4.0.33
Ant:           Apache Ant(TM) version 1.10.17 compiled on April 6 2026
Launcher JVM:  17.0.20.1 (Ubuntu 17.0.20.1+1-1-22.04-Ubuntu)
Daemon JVM:    /usr/lib/jvm/java-17-openjdk-amd64 (no Daemon JVM specified, using current Java home)
OS:            Linux 6.8.0-138-generic amd64

gradle --stop:停止当前版本的全部兼容 Daemon,实测回显:

Stopping Daemon(s)
1 Daemon stopped

Daemon 启动回显:--stop 后执行任意构建命令(如 gradle help),实测回显首行:

Starting a Gradle Daemon, 8 stopped Daemons could not be reused, use --status for details
Reusing configuration cache.

> Task :help

("8 stopped Daemons could not be reused" 指 JVM 参数/配置变更后旧 Daemon 不可复用,Gradle 另起新 Daemon——改过 org.gradle.jvmargs 后出现属正常。)

gradle --status:查看 Daemon 状态,运行中实测回显(节选):

   PID STATUS   INFO
1309975 IDLE     9.8.2
1277180 STOPPED  (stop command received)

全部停止后实测回显:

No Gradle daemons are running.

要点:STATUS 取值 IDLE(空闲可复用)/BUSY(执行中)/STOPPED(已退出);--status 只显示当前 Gradle 版本兼容的 Daemon。验证 Daemon 堆参数不在 --status,用 jps -v | grep GradleDaemon(实测方法见 《Gradle 9.8 配置参数详解》 5.1 节)。

4.2 任务发现三件套:tasks / projects / properties

gradle projects:列出构建包含的全部模块与层级,实测回显(--console=plain):

> Task :projects

Projects:

------------------------------------------------------------
Root project 'demo-multi'
------------------------------------------------------------

Project hierarchy:

Root project 'demo-multi'
+--- Project ':app'
\--- Project ':lib'

Project locations:

project ':app' - /app
project ':lib' - /lib

To see a list of the tasks of a project, run gradle <project-path>:tasks
For example, try running gradle :app:tasks

BUILD SUCCESSFUL in 365ms
1 actionable task: 1 executed
Configuration cache entry reused.

gradle :app:tasks:列出模块的全部任务(按分组展示),实测回显(--console=plain,节选):

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the classes of the 'main' feature.
testClasses - Assembles test classes.

Distribution tasks
------------------
assembleDist - Assembles the main distributions
distTar - Bundles the project as a distribution.
distZip - Bundles the project as a distribution.
installDist - Installs the project as a distribution as-is.

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the 'main' feature.

Help tasks
----------
artifactTransforms - Displays the Artifact Transforms that can be executed in project ':app'.
buildEnvironment - Displays all buildscript dependencies declared in project ':app'.
dependencies - Displays all dependencies declared in project ':app'.
dependencyInsight - Displays the insight into a specific dependency in project ':app'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.

(输出节选,实测首段;还有 verification/debug/build groups 等,完整清单 gradle :app:tasks --all 查看。)不带模块前缀的 gradle tasks 列出根工程任务并提示用 :app:tasks 查子模块。

gradle :app:properties:列出模块全部项目属性(依赖管理、发布配置排障常用),实测回显(节选首部):

> Task :app:properties

------------------------------------------------------------
Project ':app'
------------------------------------------------------------

allprojects: [project ':app']
ant: org.gradle.api.internal.project.DefaultAntBuilder@2bbf834
antBuilderFactory: org.gradle.api.internal.project.DefaultAntBuilderFactory@1451e7d0
application: extension 'application'
artifacts: org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorated@348276da

(输出节选,实测首部;全量数十项,建议 -q :app:properties | grep <关键字> 过滤。)

gradle help --task test:查单个任务的详细说明与参数(不执行),实测回显(节选):

Description
     Runs the test suite.

Group
     verification

BUILD SUCCESSFUL in 388ms

任务参数部分(实测完整列出):

     --fail-fast     Stops test execution after the first failed test.
     --no-fail-fast     Disables option --fail-fast.
     --test-dry-run     Simulate test execution.
     --no-test-dry-run     Disables option --test-dry-run.
     --tests     Sets test class or method name to be included (in addition to the test task filters), '*' is supported.
     --rerun     Causes the task to be re-run even if up-to-date.

4.3 构建主链:build / test / run / clean / jar

gradle clean:删除各模块 build/ 目录,实测回显:

BUILD SUCCESSFUL in 393ms
2 actionable tasks: 2 executed

gradle build:全量构建(编译+测试+打包),实测回显见 3 节前置步骤;跳过测试的变体见 4.6 节 -x test。

gradle test:仅执行测试任务,实测回显(命中构建缓存时):

> Task :lib:test FROM-CACHE

BUILD SUCCESSFUL in 433ms
5 actionable tasks: 2 from cache, 3 up-to-date

强制重跑某次测试:gradle test --rerun(--rerun 是 9.x 单任务重跑标志)。测试产物位置(实测目录清单):

ls lib/build/test-results/test/      # XML 结果
ls lib/build/reports/tests/test/     # HTML 报告

实测回显:

TEST-com.example.multi.LibraryTest.xml  com.example.multi.LibraryTest
binary  css  index.html  js

gradle run:运行 application 插件声明的主类(本工程 app 模块,main 类打印 Guava ImmutableList.of("a", "b")),实测回显:

> Task :app:run
[a, b]

BUILD SUCCESSFUL in 434ms
4 actionable tasks: 1 executed, 3 up-to-date
Configuration cache entry reused.

(单模块 demo-app 工程的实测回显为 Hello World!,见 《Ubuntu 22.04 安装 Gradle 9.8 指南》 6.3 节。)传递 JVM 参数给应用:gradle run --args='--port 8080'。

gradle jar / gradle installDist:jar 打模块 jar(lib/build/libs/lib.jar);installDist 组装可直接执行的发行目录(app/build/install/<工程名>/bin/<工程名> 启动脚本),distZip/distTar 出压缩包。产物均在各模块 build/ 下。

4.4 工程生成:init / wrapper

gradle init:交互式/参数化生成新工程骨架,核心参数 --type(java-application/java-library/java-gradle-plugin/kotlin-application/basic/...)、--dsl(kotlin/groovy)、--test-framework、--package、--project-name、--no-split-project。完整实测过程与生成物见 《Ubuntu 22.04 安装 Gradle 9.8 指南》 6.1 节。

gradle wrapper:生成/更新工程内 Wrapper(gradlew、gradle-wrapper.jar、gradle-wrapper.properties),实测回显:

> Task :wrapper UP-TO-DATE

BUILD SUCCESSFUL in 374ms
1 actionable task: 1 up-to-date

锁定版本写法 gradle wrapper --gradle-version 9.8.2;生成的 gradle-wrapper.properties 实测内容(distributionUrl、networkTimeout=10000、retries=0 等逐项说明)见安装篇 7.2 节。日常执行一律用 ./gradlew <任务> 替代 gradle <任务> 以保证版本一致。

4.5 依赖分析:dependencies / dependencyInsight / buildEnvironment

gradle :app:dependencies --configuration runtimeClasspath:打印指定配置的依赖树,实测回显:

runtimeClasspath - Runtime classpath of source set 'main'.
\--- project ':lib'
     +--- org.apache.commons:commons-math3:3.6.1
     \--- com.google.guava:guava:33.5.0-jre
          +--- com.google.guava:failureaccess:1.0.3
          +--- com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava
          +--- org.jspecify:jspecify:1.0.0
          +--- com.google.errorprone:error_prone_annotations:2.41.0
          \--- com.google.j2objc:j2objc-annotations:3.1

解读:app 的运行时类路径经模块依赖 :lib 传递到 guava/commons-math3 及其传递依赖——注意 guava 能出现在这里是因为 lib 以 api 声明(implementation 声明的依赖不进入下游类路径,实测对比见 《Gradle 9.8 配置参数详解》 5.8 节)。不带 --configuration 时打印全部配置,输出很长,建议始终指定。

gradle :app:dependencyInsight --dependency guava --configuration runtimeClasspath:解释"某个依赖为何/以何版本进入类路径"(版本冲突排障利器),实测回显(节选):

com.google.guava:guava:33.5.0-jre
  Variant jreRuntimeElements:
    | Attribute Name                 | Provided     | Requested    |
    |--------------------------------|--------------|--------------|
    | org.gradle.status              | release      |              |
    | org.gradle.category            | library      | library      |
    | org.gradle.dependency.bundling | external     | external     |
    | org.gradle.jvm.environment     | standard-jvm | standard-jvm |
    | org.gradle.jvm.version         | 8            | 21           |
    | org.gradle.libraryelements     | jar          | jar          |

(输出节选,实测首部;其后还有 Selection reasons 与依赖路径 项目 :lib → guava。)

gradle :app:buildEnvironment:打印构建脚本本身的插件/类路径依赖(buildscript 排障用)。

4.6 常用全局标志详解(gradle --help 实测全表节选)

gradle --help 实测输出(节选常用项,默认值为官方标注):

  --help, -?, -h                     Shows this help message.
  --show-version, -V                 Prints version information and continues.
  --version, -v                      Prints version information and exits.
  --debug, -d                        Sets log level to debug. Includes the normal stacktrace.
  --full-stacktrace, -S              Prints the full (very verbose) stacktrace for all exceptions.
  --info, -i                         Sets the log level to info.
  --quiet, -q                        Logs errors only.
  --stacktrace, -s                   Prints the stacktrace for all exceptions.
  --warn, -w                         Sets the log level to warn.
  --console                          Specifies which type of console output to generate. Supported values are 'plain', 'colored', 'auto' (default), 'rich', or 'verbose'.
  --gradle-user-home, -g             Specifies the Gradle user home directory. Default is ~/.gradle.
  --offline                          Runs the build without accessing network resources.
  --project-dir, -p                  Specifies the start directory for Gradle. Default is the current directory.
  --project-prop, -P                 Sets a project property for the build script (for example, -Pmyprop=myvalue).
  --refresh-dependencies, -U         Refreshes the state of dependencies.
  --system-prop, -D                  Sets a JVM system property (for example, -Dmyprop=myvalue).
  --continue                         Continues task execution after a task failure.
  --continuous, -t                   Enables continuous build. Gradle does not exit and will re-execute tasks when task file inputs change.
  --dry-run, -m                      Runs the build with all task actions disabled.
  --exclude-task, -x                 Specifies a task to exclude from execution.
  --rerun-tasks                      Ignores previously cached task results.
  --build-cache                      Enables the Gradle build cache. Gradle will try to reuse outputs from previous builds.
  --no-build-cache                   Disables the Gradle build cache.
  --configuration-cache              Enables the configuration cache. ...
  --max-workers                      Configures the maximum number of concurrent workers Gradle is allowed to use.
  --parallel                         Builds projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use.
  --priority                         Specifies the scheduling priority for the Gradle daemon and all processes launched by it. Supported values are 'normal' (default) or 'low'.

(输出节选,实测常用段;完整表 gradle --help。)逐项实测与说明:

--offline:离线模式,只信本地缓存不访问网络。实测(依赖已缓存时):

gradle :app:build --offline
BUILD SUCCESSFUL in 378ms
7 actionable tasks: 7 up-to-date

适用:内网隔离、断网开发、加速无变更构建;本地缓存缺依赖时该标志直接报 No cached version of ... available for offline mode.。

-x test(--exclude-task):从任务图剔除指定任务。实测:

gradle build -x test
BUILD SUCCESSFUL in 590ms
7 actionable tasks: 5 executed, 2 from cache

test 及其专属上游(compileTestJava)被跳过,主链照常。多任务跳过可连写 -x test -x javadoc。

--refresh-dependencies:强制重新校验全部依赖元数据与校验和(相当于"依赖层强制刷新")。实测:

gradle :lib:build --refresh-dependencies
BUILD SUCCESSFUL in 30s
4 actionable tasks: 4 up-to-date

对比同任务无标志的毫秒级耗时,30 秒即重新向 Maven Central 校验元数据的代价——网络排障(验证代理/镜像是否打通)时使用,日常勿开。

--parallel / --max-workers=N:并行构建与 Worker 上限。实测 gradle clean build --max-workers=1(单 Worker 串行):

BUILD SUCCESSFUL in 649ms
11 actionable tasks: 7 executed, 4 from cache

多模块工程并行收益随模块数增长;--max-workers 默认取 CPU 核数,共享构建机上可与 Daemon 堆上限(org.gradle.jvmargs)联动限资源。

--dry-run(-m):空跑任务图,只打印不执行。实测:

gradle build --dry-run
:lib:test SKIPPED
:lib:check SKIPPED
:lib:build SKIPPED

BUILD SUCCESSFUL in 381ms

--continue:某任务失败后继续执行其余无依赖任务(CI 收集全部失败项时常用)。

--console=plain:纯文本输出(CI 日志友好;本文多数回显采用该模式,默认 auto 会输出进度条动画)。

-P<属性名>=<值> / -D<系统属性>=<值>:命令行注入项目属性/系统属性,构建脚本经 providers.gradleProperty("名") / System.getProperty("名") 读取;临时开代理可 -Dhttps.proxyHost=... -Dhttps.proxyPort=...。

--scan:生成构建分析报告(耗时分布、依赖树、配置缓存命中)。⚠️ 免费版需上传到 scans.gradle.com 云端查看,涉及构建数据外发,内网/敏感工程不要使用(本文遵从数据安全纪律未实测,行为描述以官方文档为准:执行后终端给出扫描报告 URL,需在浏览器确认后查看)。内网替代品为自建 Develocity/Gradle Enterprise 或本地 build/reports/problems/problems-report.html(构建结束自动提示的本地报告,实测可见)。

--continuous(-t):监视文件变更自动重跑(Ctrl+C 退出),配合 run/test 做开发循环。

--rerun-tasks:忽略全部缓存与增量判定强制全量重跑(排障用,代价大)。

4.7 Daemon 生命周期小结

命令作用实测回显要点
gradle --status查看兼容 Daemon 列表PID STATUS(IDLE/BUSY/STOPPED) INFO(版本)
gradle --stop停止当前版本全部 DaemonStopping Daemon(s) / N Daemon(s) stopped
(自动)Starting a Gradle Daemon...无可复用 Daemon 时新起提示不可复用的停止数
`jps -vgrep GradleDaemon`验证 Daemon JVM 参数

Daemon 默认 3 小时空闲自退(org.gradle.daemon.idletimeout=10800000 可调);org.gradle.jvmargs 变更后旧 Daemon 自动淘汰另起(4.1 节实测的 "8 stopped Daemons could not be reused" 即多次参数实验的累积)。

五、注意事项

  1. 工程级版本一致性:多机协作/CI 一律用 ./gradlew(Wrapper 锁版本),直接 gradle 走本机版本,可能与工程声明不符。
  2. --scan 数据外发:见 4.6 节说明,内网慎用;本地报告在 build/reports/problems/。
  3. 缓存与"为什么没重新跑":结果 UP-TO-DATE/FROM-CACHE/SKIPPED 分别对应增量命中/缓存命中/空跑剔除;强制重跑单任务用 --rerun,全量用 --rerun-tasks。
  4. 任务前缀:多模块工程里 gradle build 会全模块执行;只要某模块用 :app:build,顺带构建其依赖模块用 gradle :app:buildDependents。
  5. CI 环境建议:--console=plain --no-daemon(或保留 Daemon 但用完 --stop),并显式 --max-workers 限并发防资源挤兑。

六、常见问题

Q1:gradle <task> 报 "Task 'xxx' not found in root project"? 任务名打错或任务在子模块:先 gradle tasks(根)与 gradle :app:tasks(模块)找正确名字;多模块任务记得加 :模块: 前缀。

Q2:命令行没输出依赖下载过程,怎么确认下载了? Gradle 默认不逐行打印下载,加 --info 可见 Downloading https://... 行;或看 ~/.gradle/caches/modules-2 的文件时间戳。

Q3:--offline 报 No cached version? 本地缓存没有该依赖且离线禁网。去掉 --offline 联网拉一次(配好仓库/代理),或把依赖预先拷入本机缓存/Nexus。

Q4:gradle run 传参数给主类? gradle run --args='--port 8080 --debug';参数含空格注意 shell 引号。

Q5:改了 gradle.properties 后构建变慢并提示 Starting a Gradle Daemon? 环境参数变更使旧 Daemon 失效,Gradle 自动重建(一次性开销);确认参数生效用 jps -v | grep GradleDaemon(4.7 节)。

Q6:测试想只跑某一个类/方法? gradle :lib:test --tests "com.example.multi.LibraryTest" 或方法级 --tests "com.example.multi.LibraryTest.someMethod*"(help --task test 实测列出的 --tests 支持 * 通配)。

七、参考链接

  1. Gradle Usermanual · Command-Line Interface(全局标志全表):https://docs.gradle.org/current/userguide/command_line_interface.html
  2. Gradle Usermanual · Gradle Daemon:https://docs.gradle.org/current/userguide/gradle_daemon.html
  3. Gradle Usermanual · Inspecting Dependencies(dependencies/dependencyInsight):https://docs.gradle.org/current/userguide/inspecting_dependencies.html
  4. Gradle Usermanual · Wrapper:https://docs.gradle.org/current/userguide/gradle_wrapper.html
  5. Build Scans 官方说明:https://docs.gradle.org/current/userguide/build_scans.html
  6. 本系列篇目:《Gradle 9.8.2 介绍与选型指南》、《Ubuntu 22.04 安装 Gradle 9.8 指南》、《Gradle 9.8 配置参数详解》