Bazel 9.3 常用 CLI 命令详解
Bazel 9.3.0 命令树逐条实测:build/test/run/query/cquery/aquery/clean/info/mod/coverage 等 24 个命令与常用标志、失败测试与覆盖率报告实录、--config 语法,以及 Bazelisk 锁版本等专属能力,回显逐行为真。
Bazel 9.3 常用 CLI 命令详解
目标:系统过一遍 Bazel 9.3.0 的命令树——
build/test/run/query/cquery/aquery/clean/info/mod/coverage等逐条实测,覆盖--config语法、查询表达式输出与 Bazelisk 版本管理器专属能力。全部命令在 Ubuntu 22.04 真实环境执行,回显逐行为真。
一、环境信息
- 操作系统:Ubuntu 22.04.4 LTS(x86_64),12 核 / 32GB 内存,root 用户
- Bazel:9.3.0(官方 APT 仓库安装,见 《Ubuntu 22.04 安装 Bazel 9.3.0 指南》)
- Bazelisk:v1.28.1(版本管理器,见同篇第五节)
- 实测工程:
/opt/data/quzuo/tmp/bazel/demo-app(cc_librarygreet+ cc_binaryhello+ cc_testgreet_test,工程结构与MODULE.bazel/BUILD内容见安装篇第七节) - 失败测试演示工程:
/opt/data/quzuo/tmp/bazel/fail-demo(含一个必然失败的 gtest 用例)
二、工具概览
2.1 命令树全貌
bazel help 给出的官方命令清单(实测全文):
Usage: bazel <command> <options> ...
Available commands:
aquery Analyzes the given targets and queries the action graph.
build Builds the specified targets.
canonicalize-flags Canonicalizes a list of Bazel options.
clean Removes output files and optionally stops the server.
coverage Generates code coverage report for specified test targets.
cquery Analyzes the given targets with the configuration and queries the specified targets' dependency graph.
dump Dumps the internal state of the Bazel server.
fetch Fetches external repositories that are prerequisites for the specified targets.
help Prints usage for all commands or for one specific command.
info Displays runtime info about the bazel server, or about a specific location relating to the bazel server process, for the specified targets.
license Prints the license of this copy of Bazel.
mobile-install Installs targets to mobile devices.
mod Queries the Bzlmod module graph.
print_action Prints the command line args for compiling a file.
query Executes a dependency graph query.
run Runs the specified target.
shutdown Stops the Bazel server.
test Builds and runs the specified test targets.
vendor Fetches external repositories into a folder specified by the flag --vendor_dir.
version Prints version information for the installed Bazel.
Getting more help:
bazel help <command> Prints help and flags for <command>.
bazel help startup_options
Flags for the JVM hosting Bazel.
bazel help target-syntax
Explains the syntax for specifying and building targets.
bazel help info-keys Displays a list of keys used by the info command.
命令树确认两点(Bazel 9.3.0 实测):共计 24 个命令;sync 与 cinfo 已不在清单中——sync 在 Bazel 8 后随 WORKSPACE 机制退役被移除,实测调用会直接报错(见 2.2 节),cinfo 同样报 "Command 'cinfo' not found"。
2.2 已移除命令的实测行为
bazel sync //...
实测回显:
Command 'sync' not found. Try 'bazel help' for more information.
替代方式:仓库级同步职责由 bzlmod 体系接管(bazel fetch 拉取依赖、bazel mod graph 查看模块图)。
三、前置条件
- Bazel 9.3.0 就绪:
bazel --version→bazel 9.3.0; - 冒烟工程构建通过(
bazel build //:hello,工程见安装篇第七节); - 工作区
.bazelrc已配置(配置项详见配置篇):build:dbg -c dbg、build:opt -c opt --strip=always、test --test_output=errors等。
四、各命令详解
4.1 bazel build:构建目标
最核心命令。目标用标签寻址,// 开头为主仓库绝对标签,:name 为包内目标。
bazel build //:hello
实测回显(增量):
INFO: Analyzed target //:hello (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //:hello up-to-date:
bazel-bin/hello
INFO: Elapsed time: 0.084s, Critical Path: 0.00s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total actions
常用形态(实测均通过):
bazel build //... # 当前包及全部子包(递归)
bazel build //:hello //:greet_test # 多目标并行构建
bazel build :all # 当前包内全部目标
💡 说明:
//...在根包场景等价于构建所有目标;输出产物链接在bazel-bin(二进制)、bazel-genfiles、bazel-out等便捷符号链接下,物理路径在输出基目录~/.cache/bazel/_bazel_root/<工作区哈希>/execroot/...。
4.2 bazel test:构建并运行测试
bazel test //:greet_test
实测回显:
INFO: Analyzed target //:greet_test (0 packages loaded, 0 targets configured).
INFO: Found 1 test target...
Target //:greet_test up-to-date:
bazel-bin/greet_test
INFO: Elapsed time: 0.102s, Critical Path: 0.00s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total actions
//:greet_test PASSED in 0.0s
失败用例的输出策略(配置篇 5.10 节实测过的 --test_output=errors)在失败测试上体现:
cd /opt/data/quzuo/tmp/bazel/fail-demo && bazel test //:bad_test 2>&1 | grep -A4 Failure
实测回显:
bad_test.cc:3: Failure
Expected equality of these values:
1
2
测试日志与覆盖率数据落盘位置(实测路径):
cat bazel-testlogs/greet_test/test.log | head -6
实测回显:
Running main() from gmock_main.cc
[==========] Running 2 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 2 tests from GreetTest
[ RUN ] GreetTest.DefaultGreeting
[ OK ] GreetTest.DefaultGreeting (0 ms)
4.3 bazel run:构建并执行
bazel run //:hello
bazel run //:hello -- World
实测回显(输出节选,两行分别为不带参与带参运行结果):
INFO: Running command line: bazel-bin/hello
Hello, Bazel!
INFO: Running command line: bazel-bin/hello <args omitted>
Hello, World!
💡 说明:
--之后的参数原样传给目标二进制。bazel run会先确保目标 up-to-date 再执行,等价「构建 + 就地运行」,是 CLI 工具类项目(格式化器、生成器等)的标准使用方式。
4.4 bazel query:目标依赖图查询
bazel query //...
实测回显:
//:greet_test
//:hello
//:greet
按规则类型过滤(kind() 表达式):
bazel query 'kind(cc_library, //...)'
实测回显:
//:greet
传递依赖闭包(deps() 表达式,截取前 12 行):
bazel query 'deps(//:hello)' | head -12
实测回显:
//:hello
//:greet
//:greet.h
//:main.cc
//:greet.cc
@rules_cc//cc:cc_binary.bzl
@rules_cc//cc:cc_library.bzl
@rules_cc//cc:action_names.bzl
@rules_cc//cc:find_cc_toolchain.bzl
...(共 96 行)
路径搜索(somepath(),查询两个目标间的依赖路径):
bazel query 'somepath(//:greet_test, @googletest//:gtest)' | head -6
实测回显:
//:greet_test
@googletest//:gtest
查询支持集合运算与通配,bazel help query 有完整语法说明(deps/rdeps/labels/filter/kind/somepath/allpaths 等)。
4.5 bazel cquery:带配置的查询
cquery 在分析阶段之后执行,能给出带配置哈希的精确目标信息:
bazel cquery //:hello
实测回显:
//:hello (a7a71fd)
💡 说明:括号内
a7a71fd是该目标的配置哈希(编译模式、平台、标志组合的摘要)——同一条规则在 fastbuild/dbg/opt 下会得到不同配置哈希,这正是构建可重现性的基石。需要产物清单时用--output=files:
bazel cquery //:hello --output=files
实测回显:
bazel-out/k8-fastbuild/bin/hello
4.6 bazel aquery:动作图查询
比 cquery 更低一层,直接查询动作(Action)——是核对「某个目标到底执行了哪些命令」的工具。
bazel aquery //:hello
实测回显(节选):
action {
mnemonic: "CppCompile"
execution_platform: "//host:x86_64"
arguments: "/usr/bin/gcc"
arguments: "-U_FORTIFY_SOURCE"
...
primary_output: "bazel-out/k8-fastbuild/bin/_objs/hello/hello/hello.pic.o"
}
要看完整命令行用 --output=commands(配置篇 5.4 节已贴出 main.cc 的完整 gcc 命令行,其中可核对 rc 注入的 -Wall)。
⚠️ 注意(排障实录):
--output=command(单数)不是合法取值,实测报错--output=command does not exist; expected one of proto, streamed_proto, textproto, jsonproto, text, commands, summary——正确拼写是复数commands。
4.7 bazel clean:清理输出
bazel clean
实测回显:
INFO: Output base moved to /root/.cache/bazel/_bazel_root/fa1d9e89156fda47cf833dc1dc609557/output_base_moved_to_4120279917, will delete on next shutdown.
INFO: Starting clean.
💡 说明:
bazel clean把输出基目录整体挪走(下次构建全量重来,但外部依赖仓库缓存仍在);bazel clean --expunge连服务器进程与输出基目录一起删除(更彻底也更慢,仅在磁盘紧张或状态异常时用)。
4.8 bazel info:运行时状态查询
bazel info
实测回显(关键键,节选):
release: release 9.3.0
output_base: /root/.cache/bazel/_bazel_root/fa1d9e89156fda47cf833dc1dc609557
execution_root: /opt/data/quzuo/tmp/bazel/demo-app
output_path: /root/.cache/bazel/_bazel_root/fa1d9e89156fda47cf833dc1dc609557/execroot/_main/bazel-out
repository_cache: /root/.cache/bazel/_bazel_root/cache/repos/v1
server_pid: 1280832
java-home: /root/.cache/bazel/_bazel_root/install/bf018ed227128835327c556cff5c0ff0/embedded_tools/jdk
java-runtime: OpenJDK Runtime Environment (build 25.0.2+10-LTS) by Azul Systems, Inc.
max-heap-size: 536MB
local_resources: RAM=32050MB, CPU=12.0
committed-heap-size: 113MB
单键查询与完整键清单:
bazel info server_pid
bazel help info-keys
4.9 bazel mod:模块依赖图查询
bazel mod graph | head -5
实测回显:
<root> (demo_app@1.0.0)
|___googletest@1.18.0.bcr.1
| |___abseil-cpp@20260526.0
| | |___config_helpers@2.1.0 ...
| |___re2@2026-04-01.bcr.1
💡 说明:
mod是 bzlmod 时代的依赖治理入口,子命令有graph(模块图)、deps(模块依赖展开)、explain(版本收敛解释,排查「为什么用了 1.2.3」)等。依赖声明与 override 的写法见配置篇 5.11 节。
4.10 bazel coverage:覆盖率
time bazel coverage //:greet_test
实测回显(输出节选;首次需拉取覆盖率工具,实测耗时 84.4 秒):
INFO: Analyzed target //:greet_test (43 packages loaded, 641 targets configured).
INFO: Found 1 test target...
INFO: From CcCodeCoverage:
Target //:greet_test up-to-date:
bazel-bin/greet_test
bazel-bin/greet_test.runfiles_manifest
bazel-out/k8-fastbuild/bin/greet_test
...
INFO: Elapsed time: 84.376s, Critical Path: 13.19s
INFO: 43 processes: 16 internal, 5 linux-sandbox, 22 local.
Executed 1 out of 1 tests: 1 test passes.
INFO: There are 1 local-execution actions among the cached ones. Enable -- experimental_execution_strategies to see them.
INFO: Build completed successfully, 43 total actions
//:greet_test PASSED in 0.0s
INFO: LCOV coverage report is located at bazel-out/_coverage/_coverage_report.dat
INFO: Coverage report is located at /root/.cache/bazel/_bazel_root/fa1d9e89156fda47cf833dc1dc609557/execroot/_main/bazel-out/k8-fastbuild/testlogs/_coverage/coverage.dat
覆盖率报告内容(LCOV 格式,SF 文件 / LF 总行数 / LH 命中行数):
grep -E '^(SF|LF|LH)' bazel-out/_coverage/_coverage_report.dat | head -6
实测回显:
SF:external/+module+googletest+/googletest/include/gtest/internal/gtest-port.h
LF:1473
LH:0
SF:greet.cc
LF:1
LH:1
(greet.cc LF:1/LH:1 即该文件 1 行源码 1 行被测试覆盖;头文件命中为 0 属 C++ 覆盖率的常见噪声,可用 --instrumentation_filter 缩小统计范围。)
4.11 bazel fetch / bazel vendor:依赖拉取
bazel fetch //...
实测回显:
INFO: All external dependencies for all files fetched successfully.
bazel vendor
实测回显:
ERROR: Error while parsing option: --vendor_dir is required to use vendor command.
💡 说明:
fetch把@...外部仓库依赖下载到仓库缓存;vendor是 Bazel 8 新增的「依赖落盘进版本库」机制,必须先在 rc 里指定build --vendor_dir=<目录>才能使用。
4.12 辅助命令:version / license / dump / shutdown / canonicalize-flags / print_action / mobile-install
bazel version
实测回显:
Build label: 9.3.0
Build target: @@//src/main/java/com/google/devtools/build/lib/bazel:BazelServer
Build time: Wed Oct 07 14:46:24 2026 (1791384384)
Build timestamp: 1791384384
Build timestamp as int: 1791384384
bazel license | head -3
实测回显:
Bazel is licensed under the Apache License, Version 2.0.
For more information, please refer to the LICENSE file online:
https://www.apache.org/licenses/LICENSE-2.0
bazel dump --rules | head -4
实测回显:
2015-01-01 00:00:00,000 (0) Bazel 9.3.0
## 1: name call_count module
2: filegroup 172 @@rules_cc+//cc:cc_library.bzl
3: cc_library 170 @@rules_cc+//cc:cc_library.bzl
bazel shutdown
bazel info server_pid
实测回显(shutdown 无输出;info 触发服务器重新拉起并给出新 PID):
Starting local Bazel server (9.3.0) and connecting to it...
1795220
bazel canonicalize-flags -- --jobs=4 --local_resources=ram=8192
实测回显:
--jobs=4
--local_resources=ram=8192.0
bazel print_action --compile_one_dependency greet.cc
实测回显(节选):
Set of output files:
bazel-out/k8-fastbuild/bin/_objs/greet/greet/greet.pic.o
Set of actions that will be executed:
command: '/usr/bin/gcc' '-U_FORTIFY_SOURCE' ...
💡 说明:
print_action --compile_one_dependency <源文件>直接回答「这个文件是用哪条命令编出来的」,配合--output=command(print_action 自有选项)可输出完整命令行,是 IDE 与调试场景的利器。mobile-install面向 Android 设备增量部署,无 Android 工程时不可用。
4.13 --config 语法:命名配置的启用方式
--config=名称 启用 rc 中 命令:名称 定义的配置块(定义语法与配置块清单见配置篇 5.1 节)。实测本工程 rc 中定义的 dbg/opt:
bazel build --config=dbg //:hello && readlink bazel-bin
bazel build --config=opt //:hello && readlink bazel-bin
实测回显:
k8-dbg
k8-opt
规则要点(配置篇已实测验证):--config 可叠加(命令行可写多个);同名配置块跨 rc 文件为追加;--config 引用的配置块自身还可再引用其他 --config(官方支持配置链)。
五、Bazelisk 专属能力
Bazelisk(官方版本管理器,安装见安装篇第五节)除按 .bazelversion 自动选版外,还有一组环境变量能力(来源:bazelisk 官方 README,2026-10-20 经 npm 源核对)。
5.1 USE_BAZEL_VERSION:临时锁版本(实测)
USE_BAZEL_VERSION=9.3.0 bazelisk version | grep 'Build label'
USE_BAZEL_VERSION=8.8.1 bazelisk version | grep -E 'Build label|Build time'
实测回显:
Build label: 9.3.0
Build label: 8.8.1
Build time: Thu Sep 24 20:14:55 2026 (1790280895)
8.8.1 的 Build time(2026-09-24)与官方 Releases Atom 流发布时间一致,确认是官方二进制。解析优先级:USE_BAZEL_VERSION > .bazeliskrc > .bazelversion > latest;还支持浮动标签如 latest-1(上一稳定版)、4.x(4 系最新)。
5.2 BAZELISK_GITHUB_TOKEN:API 限流防护(引用,未实测)
官方 README 说明:在不限流就无法解析版本信息的网络里(如共享出口 IP 的 CI),用 GitHub 访问令牌规避匿名 API 限额:
# 语法参考(bazelisk 官方 README):export BAZELISK_GITHUB_TOKEN=<你的GitHub个人令牌>
⚠️ 注意:本篇实测环境的 GitHub API 链路不可达,该项未做执行验证,仅按官方 README 引用语法;令牌只走环境变量、不要写入 rc 或脚本,避免入库泄露。
5.3 BAZELISK_BASE_URL:下载源改址(引用,未实测)
官方 README 说明:用 BAZELISK_BASE_URL 指向自托管镜像目录可让 bazelisk 从内网源下载 Bazel 二进制(受限网络/内网 CI 的标准做法)。本篇实测环境已用 USE_BAZEL_VERSION 锁定版本绕开版本清单查询,该变量未做执行验证。
六、注意事项
- 客户端-服务器模型:命令输出前常见
Starting local Bazel server或WARNING: Running Bazel server needs to be killed...(startup 选项变化触发服务器重启,见配置篇 3.3 节),属正常行为; - 便捷符号链接:
bazel-bin等是符号链接,指向输出基目录内的真实产物路径;bazel clean后它们会被重建,不要手工把构建产物提交进版本库; - 工作区边界:命令须在含
MODULE.bazel的工作区内执行,否则 bazelisk 场景会提示WARNING: Invoking Bazel in batch mode since it is not invoked from within a workspace(安装篇 5.3 节实录); --output=commands复数拼写:aquery 的命令行输出形态是commands,单数形式直接报错(4.6 节实录);sync/cinfo已移除:旧资料里的这两个命令在 9.3.0 不存在,替代见 2.1/2.2 节。
七、常见问题(FAQ)
Q1:bazel --version 与 bazel version 输出为何不同?
前者由客户端启动器直接应答(秒回);后者触达服务器进程,含 Build label/Build time 完整信息(4.12 节)。
Q2:如何确认某次构建到底执行了哪些编译命令?
bazel aquery //:target --output=commands(4.6 节),或对单文件用 bazel print_action --compile_one_dependency <file>(4.12 节)。
Q3:测试通过但想看 gtest 完整输出?
读 bazel-testlogs/<测试目标>/test.log(4.2 节);失败时用 --test_output=errors 直接打印详情,--test_output=all 打印全部输出。
Q4:多模块版本冲突怎么排查?
bazel mod explain <模块名> 解释版本收敛原因;bazel mod graph 看全图;必要时在根 MODULE.bazel 用 single_version_override 钉版本(配置篇 5.11 节)。
Q5:首次跑 coverage 为什么比 test 慢很多? coverage 首次运行要拉取覆盖率工具链并插桩编译(实测 84 秒),产物入缓存后二次执行大幅加快。
Q6:bazelisk 一直报「could not resolve the version 'latest'」?
版本清单解析走 Google Cloud Storage 接口,出网受限即超时(安装篇 5.3 节实测报错);用 USE_BAZEL_VERSION 或 .bazelversion 锁定版本即可绕开。
八、参考链接
- 官方命令行参考:https://bazel.build/reference/cli
- 官方 query 指南:https://bazel.build/query/language
- bazelisk 官方仓库:https://github.com/bazelbuild/bazelisk(README 经 npm 源核对,2026-10-20)
- 本专栏配置篇:《Bazel 9.3 配置参数详解》
- 本专栏安装篇:《Ubuntu 22.04 安装 Bazel 9.3.0 指南》
- 本专栏认知篇:《Bazel 9.3.0 介绍与选型指南》