just 命令运行器完全指南:justfile 配方语法、设置与源码级原理剖析

原创2026-09-29 23:39:431,440 阅读
文章标签:CLI开发工具任务调度

just 命令运行器完全指南:justfile 配方语法、设置与源码级原理剖析

just 是一个用 Rust 编写的命令运行器,它以受 make 启发的语法,将项目特有的常用命令(在 just 中称为"配方",Recipe)保存在名为 justfile 的文件中,让你可以通过 just RECIPE 一键运行。本文以仓库中的 README.中文.md 为骨架,结合 src/ 目录下的 Rust 源码与 tests/ 测试用例,系统讲解 just 的安装方式、配方语法、内置设置、环境变量、函数体系与底层实现原理。读完本文,你将能够独立编写跨平台、参数化、可组合的 justfile,并理解 just 的 Shell 解析、dotenv 加载与静态错误检测机制。

just 命令运行界面截图

为什么选择 just 而不是 make

just 的定位是"命令运行器"(command runner)而非"构建系统",因此它刻意规避了 make 大量针对文件构建的复杂性与特异性。核心差异包括:

  • 不需要 .PHONY 配方:make 会假设 test: 配方会生成名为 test 的文件,如果该文件已存在,make 会拒绝运行命令(输出 make: 'test' is up to date.)。而 just 中所有配方一律视为 phony(虚假目标),永远按声明执行。在 README.中文.md 的"Just 避免了 Make 的哪些特异性"一节对此有详细对比。
  • 跨平台:支持 Linux、macOS 与 Windows,无需额外依赖;错误信息具体且带上下文,语法错误会与产生它们的源码位置一同报告。
  • 静态错误检测:未知配方与循环依赖在运行之前就被报告,而非等到执行到那一步才报错。
  • 配方参数:配方可以接收命令行参数(见下文"配方参数")。
  • .env 加载:原生支持 dotenv 环境变量注入。
  • 任意语言配方:通过 Shebang 配方,可用 Python、Node.js、Perl、Ruby、Nushell 等任意语言编写配方。
  • 任意子目录调用:just 会从当前目录向上递归搜索 justfile。

安装 just

预备知识:sh 与 Shell 配置

just 可以在任何拥有合适 sh 的系统上运行,包括 Linux、macOS 和 BSD。在 Windows 上,可以使用 Git for Windows 等工具提供的 sh;如果你不愿意安装 sh,也可以通过 shell 设置指定其他 Shell,例如 PowerShell 或 cmd.exe:

# 使用 PowerShell 替代 sh:
set shell := ["powershell.exe", "-c"]

hello:
  Write-Host "Hello, world!"
# 使用 cmd.exe 替代 sh:
set shell := ["cmd.exe", "/c"]

list:
  dir

也可以用命令行参数设置 Shell:just --shell powershell.exe --shell-arg -c。(PowerShell 默认预装在 Windows 7 SP1 及更高版本上,官方更推荐 Windows 用户使用 PowerShell。)

包管理器安装

不同平台可通过对应包管理器一键安装(完整安装命令以 README.中文.md 安装章节为准,此处摘录常用项):

操作系统 包管理器 命令
Various Cargo cargo install just
Microsoft Windows Scoop scoop install just
Various Homebrew brew install just
macOS MacPorts port install just
Arch Linux pacman pacman -S just
Various Nix nix-env -iA nixpkgs.just
NixOS Nix nix-env -iA nixos.just
FreeBSD pkg pkg install just
Alpine Linux apk-tools apk add just
Fedora Linux DNF dnf install just
Gentoo Linux Portage eselect repository enable guru → emerge --sync guru → emerge sys-devel/just
Various Conda conda install -c conda-forge just
Microsoft Windows Chocolatey choco install just
Various Snap snap install --edge --classic just
Various asdf asdf plugin add just → asdf install just <version>
Various PyPI pipx install rust-just
Various npm npm install -g rust-just
Debian/Ubuntu MPR git clone 'https://mpr.makedeb.org/just' → cd just → makedeb -si
Debian/Ubuntu Prebuilt-MPR 配置好 Prebuilt-MPR 后 sudo apt install just

预制二进制文件

Linux、macOS 和 Windows 的预制二进制可在官方发布页获取,也可以一行命令安装到指定目录(将 DEST 替换为目标目录):

curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to DEST

例如安装到 ~/bin:

mkdir -p ~/bin
curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to ~/bin
export PATH="$PATH:$HOME/bin"   # 建议写入 ~/.bashrc 或 ~/.zshrc
just --help

GitHub Actions 与 Node.js 安装

CI 中可使用 extractions/setup-just 或 taiki-e/install-action 安装 just:

- uses: extractions/setup-just@v1
  with:
    just-version: 0.8 # optional semver specification, otherwise latest
- uses: taiki-e/install-action@just

Node.js 项目中可通过 just-install 包将 just 作为 npm install 的依赖自动安装,安装后 just 命令即可在 npm 脚本或 npx 中使用,避免每个开发者手动安装。

快速开始

在项目根目录创建名为 justfile 的文件:

recipe-name:
  echo 'This is a recipe!'

# 这是一行注释
another-recipe:
  @echo 'This is another recipe.'
  • just 会在当前目录及其父目录中寻找 justfile,因此可以从项目的任何子目录调用它;搜索不区分大小写(Justfile、JUSTFILE 均可),也会查找隐藏文件 .justfile。
  • 不带参数运行 just 会执行 justfile 中的第一个配方:
$ just
echo 'This is a recipe!'
This is a recipe!
  • 带参数运行指定配方:
$ just another-recipe
This is another recipe.

just 在运行每条命令前会将其打印到标准错误,这就是第一条输出出现 echo 'This is a recipe!' 的原因;以 @ 开头的行会抑制回显,所以 echo 'This is another recipe.' 未被打印。

命令失败即停止:如果一个命令返回非零退出状态,配方会立即停止。例如下面的 publish 配方中,cargo publish 只有在 cargo test 成功之后才会执行:

publish:
  cargo test
  # 前面的测试通过才会执行 publish!
  cargo publish

配方依赖:test 配方依赖 build 配方,因此 build 会先于 test 运行:

build:
  cc main.c foo.c bar.c -o main

test: build
  ./test

sloc:
  @echo "`wc -l *.c` lines of code"
$ just test
cc main.c foo.c bar.c -o main
./test
testing… all tests passed!

没有依赖的配方按命令行给出的顺序运行;依赖项总是先运行,即使它写在依赖它的配方之后(如 just test build 中 build 依旧先执行)。更多示例可参考 examples/ 目录下的 justfile 样例(如 examples/kitchen-sink.just、examples/cross-platform.just)。

配方(Recipe)基础

默认配方

不带参数调用 just 时运行第一个配方,它通常是项目中最常用的命令,例如 cargo test;也可以通过依赖关系让默认配方聚合多个任务:

default: lint build test

build:
  echo Building…

test:
  echo Testing…

lint:
  echo Linting…

若没有合适的默认配方,可以在 justfile 开头放一个列出可用配方的配方:

default:
  just --list

列出可用配方

just --list 按字母顺序列出配方,just --summary 以更紧凑的单行形式输出:

$ just --list
Available recipes:
    build
    test
    deploy
    lint
$ just --summary
build test deploy lint

--unsorted 选项按 justfile 中出现的原始顺序打印;--list-heading 定制标题文本(同时替换标题和其后的换行,若传空字符串则完全抑制标题行),--list-prefix 定制缩进前缀:

$ just --list --unsorted
Available recipes:
    test
    build
$ just --list --list-heading $'Cool stuff…\n'
Cool stuff…
    test
    build
$ just --list --list-prefix ····
Available recipes:
····test
····build
$ just --list --list-heading ''
    test
    build

若默认配方为 @just --list,还应注意加上 --justfile {{justfile()}}:否则在 just -f /some/distant/justfile -d . 这类场景下,配方里的 just --list 不会使用你提供的文件,而会在当前路径寻找 justfile,甚至报出 No justfile found。

别名

别名允许用其他名称调用配方:

alias b := build

build:
  echo 'Building!'
$ just b
build
echo 'Building!'
Building!

别名相关的解析逻辑可在 src/alias.rs 中查看。

依赖:前期依赖与后续依赖

配方的正常依赖(前期依赖)总是在配方开始前运行。此外,just 还支持后续依赖,用 && 表示,它们在配方之后运行:

a:
  echo 'A!'

b: a && c d
  echo 'B!'

c:
  echo 'C!'

d:
  echo 'D!'

运行 just b 输出依次为 A、B、C、D。

just 不支持在配方中间运行另一个配方,但可以在配方中间递归调用 just(如 just c);这种方式有局限:子 just 是全新进程,赋值会被重新计算、依赖可能运行两次、命令行参数不会传入子进程。

设置(Settings)

设置控制 just 的解释与执行行为。每个设置最多指定一次,可出现在 justfile 的任何位置。例如:

set shell := ["zsh", "-cu"]

foo:
  # this line will be run as `zsh -cu 'ls **/*.txt'`
  ls **/*.txt

设置一览表

名称 值 默认 描述
allow-duplicate-recipes boolean False 允许在 justfile 后面出现的配方覆盖之前的同名配方
allow-duplicate-variables boolean False 允许在 justfile 后面出现的变量覆盖之前的同名变量
dotenv-filename string - 如果有自定义名称的 .env 环境变量文件的话,则将其加载
dotenv-load boolean False 如果有 .env 环境变量文件的话,则将其加载
dotenv-path string - 从自定义路径中加载 .env 环境变量文件,文件不存在将会报错,可以覆盖 dotenv-filename
dotenv-required boolean False 如果 .env 环境变量文件不存在的话,需要报错
export boolean False 将所有变量导出为环境变量
fallback boolean False 如果命令行中的第一个配方没有找到,则在父目录中搜索 justfile
ignore-comments boolean False 忽略以 # 开头的配方行
positional-arguments boolean False 传递位置参数
shell [COMMAND, ARGS…] - 设置用于调用配方和评估反引号内包裹内容的命令
tempdir string - 在 tempdir 位置创建临时目录,而不是系统默认的临时目录
windows-powershell boolean False 在 Windows 上使用 PowerShell 作为默认 Shell(废弃,建议使用 windows-shell)
windows-shell [COMMAND, ARGS…] - 设置用于调用配方和评估反引号内包裹内容的命令

Bool 类型的设置可以简写为 set NAME,等价于 set NAME := true。在源码 src/settings.rs 中,Settings 结构体完整定义了上述字段,并定义了两个关键常量:默认 Shell 为 sh、默认参数为 ["-cu"];Windows 下若启用 windows_powershell,则使用 powershell.exe -NoLogo -Command。Settings::shell() 方法的优先级逻辑与 README 中"配置 Shell"一节完全对应(见下文)。

允许重复的配方与变量

set allow-duplicate-recipes

@foo:
  echo foo

@foo:
  echo bar

just foo 输出 bar(后定义覆盖先定义),默认 false 时重复定义会报错。变量同理,set allow-duplicate-variables 后同名变量取最后一个定义。

环境变量加载(dotenv)

只要 dotenv-load、dotenv-filename、dotenv-path、dotenv-required 中任意一项被设置,just 就会尝试从文件加载环境变量:

  • dotenv-path:在指定路径搜索文件,路径可以是绝对路径或基于当前工作路径的相对路径;
  • dotenv-filename:在指定相对路径及其所有上层目录中搜索该文件;
  • 若两者都未设置但设置了 dotenv-load 或 dotenv-required,则在当前工作路径及其上层目录中寻找名为 .env 的文件;
  • 找不到文件不报错,除非设置了 dotenv-required。

从文件加载的变量是环境变量而非 just 变量,因此在配方和反引号中必须通过 $VARIABLE_NAME 访问。例如 .env 内容:

# a comment, will be ignored
DATABASE_ADDRESS=localhost:6379
SERVER_PORT=1337

justfile 内容:

set dotenv-load

serve:
  @echo "Starting server with database $DATABASE_ADDRESS on port $SERVER_PORT…"
  ./server --database $DATABASE_ADDRESS --port $SERVER_PORT

just serve 将输出 Starting server with database localhost:6379 on port 1337…。源码 src/load_dotenv.rs 展示了实现细节:dotenv-path 使用 working_directory.join(path) 直接定位,dotenv-filename 则遍历 working_directory.ancestors() 逐级向上查找,找到第一个即返回;dotenv_override 为 true 时强制覆盖已有环境变量,否则仅在环境变量不存在时写入。仓库对应的测试见 tests/dotenv.rs。

导出(export)

set export 使所有 just 变量作为环境变量导出(默认 false):

set export

a := "hello"

@foo b:
  echo $a
  echo $b
$ just foo goodbye
hello
goodbye

位置参数(positional-arguments)

set positional-arguments 为 true 时,配方参数将作为位置参数传递给命令:行式配方中 $0 是配方名,$1 起是参数:

set positional-arguments

@foo bar:
  echo $0
  echo $1
$ just foo hello
foo
hello

使用 sh 兼容 Shell(如 bash、zsh)时,$@ 展开为从 1 开始的全部位置参数;在双引号内使用 "$@" 时,含空白的参数会像双引号一样被整体传递;没有位置参数时 "$@" 与 $@ 均展开为空。下面的配方逐行打印参数:

set positional-arguments

@test *args='':
  bash -c 'while (( "$#" )); do echo - $1; shift; done' -- "$@"
$ just test foo "bar baz"
- foo
- bar baz

Shell 设置与优先级

shell 设置控制调用配方代码行与反引号内指令的命令;Shebang 配方不受影响。例如用 Python 3 执行配方行与反引号:

# use python3 to execute recipe lines and backticks
set shell := ["python3", "-c"]

# use print to capture result of evaluation
foos := `print("foo" * 4)`

foo:
  print("Snake snake snake snake.")
  print("{{foos}}")

just 把要执行的命令作为一个参数传递,因此许多 Shell 需要额外的标志(通常是 -c)来评估执行第一个参数。

常用 Shell 配置速查:

# Windows 上使用 PowerShell(推荐方式)
set windows-shell := ["powershell.exe", "-NoLogo", "-Command"]

# 遗留方式(已废弃):Windows 上使用 powershell.exe
set windows-powershell := true

# Python 3
set shell := ["python3", "-c"]

# Bash
set shell := ["bash", "-uc"]

# Z Shell
set shell := ["zsh", "-uc"]

# Fish
set shell := ["fish", "-c"]

# Nushell(可设置 light 表格模式)
set shell := ["nu", "-c"]
set shell := ['nu', '-m', 'light', '-c']

完整的多平台 PowerShell 示例见 examples/powershell.just,它同时配置了 set shell(非 Windows 平台)与 set windows-shell(Windows 平台),并演示了 Shebang 配方。

配置 Shell 的优先级(从高到低,见 src/settings.rs 中 Settings::shell() 的实现):

  1. --shell 和 --shell-arg 命令行选项(传入任一即忽略 justfile 中所有相关设置);
  2. set windows-shell := [...];
  3. set windows-powershell(废弃);
  4. set shell := [...]。

由于 windows-shell 优先级高于 shell,可以在 Windows 上用一个 Shell、其他平台用另一个 Shell。源码中 settings::tests::default_shell、default_shell_powershell、overwrite_shell 等测试用例验证了这条优先级链。

变量与替换

在变量、字符串、拼接、路径连接和替换中使用 {{…}}:

tmpdir  := `mktemp -d`
version := "0.2.7"
tardir  := tmpdir / "awesomesauce-" + version
tarball := tardir + ".tar.gz"

publish:
  rm -f {{tarball}}
  mkdir {{tardir}}
  cp README.md *.c {{tardir}}
  tar zcvf {{tarball}} {{tardir}}
  scp {{tarball}} me@server.com:release/
  rm -rf {{tarball}} {{tardir}}

路径拼接

/ 操作符用斜线连接两个字符串(即使值已有 / 也会再添加一个 /):

foo := "a" / "b"        # just --evaluate foo → a/b
bar := "a/" / "b"       # → a//b
baz := / "b"            # 1.5.0 起可构建绝对路径 → /b

/ 操作符在 Windows 上也使用 / 字符,因此应避免在 UNC 路径(以 \\?\ 开头)中使用。跨平台路径相关的变量与函数示例可参考 examples/cross-platform.just,它通过 os_family() 区分 Windows 与 Unix 的虚拟环境路径。

转义 {{

需要输出字面 {{ 时,可用 {{{{:

braces:
  echo 'I {{{{LOVE}} curly braces!'

未匹配的 }} 会被忽略,无需转义。也可把待转义文本放进插值中:echo '{{'I {{LOVE}} curly braces!'}}',或使用 {{ "{{" }}:echo 'I {{ "{{" }}LOVE}} curly braces!'。

字符串

双引号字符串支持转义序列(\t、\n、\r、\"、\\),并且支持折行续写(行尾 \ 后换行不产生换行符);单引号字符串不支持转义序列:

string-with-tab             := "\t"
string-with-newline         := "\n"
string-with-carriage-return := "\r"
string-with-double-quote    := "\""
string-with-slash           := "\\"
string-with-no-newline      := "\
"
escapes := '\t\n\r\"\\'     # 保持字面量

字符串可以包含换行符。还支持以三个单引号或三个双引号为界的缩进版本字符串,所有非空行共有的前导空白会被删除:

# 这个字符串执行结果为 `foo\nbar\n`
x := '''
  foo
  bar
'''

# 这个字符串执行结果为 `abc\n  wuv\nbar\n`
y := """
  abc
    wuv
  xyz
"""

缩进的双引号字符串处理转义序列,缩进的单引号字符串忽略转义序列;转义处理在取消缩进之后进行,取消缩进算法不考虑转义产生的空白或换行。

错误忽略

在命令前加 - 前缀,可让配方在命令失败后继续执行:

foo:
  -cat foo
  echo 'Done!'
$ just foo
cat foo
cat: foo: No such file or directory
echo 'Done!'
Done!

内置函数

just 提供丰富的内置函数(完整注册表见 src/function.rs 的 get() 函数),编写配方时非常有用。

系统信息

  • arch() — 指令集结构,可能值:"aarch64"、"arm"、"asmjs"、"hexagon"、"mips"、"msp430"、"powerpc"、"powerpc64"、"s390x"、"sparc"、"wasm32"、"x86"、"x86_64"、"xcore"。
  • os() — 操作系统,可能值:"android"、"bitrig"、"dragonfly"、"emscripten"、"freebsd"、"haiku"、"ios"、"linux"、"macos"、"netbsd"、"openbsd"、"solaris"、"windows"。
  • os_family() — 操作系统系列:"unix" 与 "windows"。
system-info:
  @echo "This is an {{arch()}} machine"
$ just system-info
This is an x86_64 machine

os_family() 是编写跨平台 justfile 的关键函数,完整示例见 examples/cross-platform.just。

环境变量

  • env_var(key) — 获取环境变量,不存在则终止执行。
  • env_var_or_default(key, default) — 获取环境变量,不存在时返回 default。
home_dir := env_var('HOME')

test:
  echo "{{home_dir}}"

调用目录

  • invocation_directory() — 获取 just 被调用时当前目录对应的绝对路径(在 just 改变路径并执行命令之前)。例如对"当前目录"下的文件调用 rustfmt,或要求命令从调用目录运行:
rustfmt:
  find {{invocation_directory()}} -name \*.rs -exec rustfmt {} \;

build:
  cd {{invocation_directory()}}; ./some_script_that_needs_to_be_run_from_here

Justfile 与可执行程序

  • justfile() — 当前 justfile 的路径。
  • justfile_directory() — 当前 justfile 所在目录。
  • just_executable() — just 可执行文件的绝对路径。
script:
  ./{{justfile_directory()}}/scripts/some_script

executable:
  @echo The executable is at: {{just_executable()}}

字符串处理

  • quote(s) — 用 '\'' 替换所有单引号并在首尾添加单引号,可为大多数 Bourne Shell 后代转义特殊字符。
  • replace(s, from, to) / replace_regex(s, regex, replacement) — 字符串替换(后者使用 Rust regex 包语法)。
  • trim(s) / trim_end(s) / trim_start(s) — 去除首尾/尾部/首部空白。
  • trim_end_match(s, substr) / trim_end_matches(s, substr) — 删除匹配的后缀(trim_end_matches 反复删除)。
  • trim_start_match(s, substr) / trim_start_matches(s, substr) — 删除匹配的前缀(trim_start_matches 反复删除)。

大小写转换

capitalize(s)(1.7.0)、kebabcase(s)、lowercamelcase(s)、lowercase(s)、shoutykebabcase(s)、shoutysnakecase(s)、snakecase(s)、titlecase(s)、uppercamelcase(s)、uppercase(s)。源码中这些函数基于 heck crate 实现(见 src/function.rs 的导入)。

路径操作

非可靠函数(可能失败,例如路径没有扩展名时停止执行):

  • absolute_path(path) — 相对路径转绝对路径(如 /foo 下 absolute_path("./bar.txt") 得 /foo/bar.txt)。
  • extension(path) — 扩展名(extension("/foo/bar.txt") → txt)。
  • file_name(path) — 文件名(→ bar.txt)。
  • file_stem(path) — 不含扩展名的文件名(→ bar)。
  • parent_directory(path) — 父目录(→ /foo)。
  • without_extension(path) — 去除扩展名(→ /foo/bar)。

可靠函数:

  • clean(path) — 删除多余分隔符、中间的 . 与 ..:clean("foo//bar") → foo/bar,clean("foo/..") → .,clean("foo/./bar") → foo/bar。
  • join(a, b…) — 拼接路径。注意:Unix 上使用 /、Windows 上使用 \,可能导致非预期行为;/ 操作符(a / b)总是使用 /,除 Windows 上明确需要 \ 外应优先考虑。

文件系统访问与错误报告

  • path_exists(path) — 路径存在返回 true(会遍历符号链接;路径不可访问或指向无效符号链接返回 false)。
  • error(message) — 终止执行并报告错误 message。

UUID 与哈希值生成

  • sha256(string) — 返回字符串的 SHA-256 十六进制哈希。
  • sha256_file(path) — 返回文件的 SHA-256 哈希。
  • uuid() — 返回随机生成的 UUID。

此外,src/function.rs 还注册了更多函数,如 num_cpus()、semver_matches()、which()、datetime()、encode_uri_component()、read()、source_directory()、module_directory() 等,可按需查阅。

配方属性(Attributes)

配方可通过属性注释改变行为:

名称 描述
[no-cd](1.9.0) 在执行配方之前不要改变目录
[no-exit-message](1.7.0) 如果配方执行失败,不要打印错误信息
[linux](1.8.0) 在 Linux 上启用配方
[macos](1.8.0) 在 macOS 上启用配方
[unix](1.8.0) 在 Unix 上启用配方
[windows](1.8.0) 在 Windows 上启用配方
[private](1.10.0) 隐藏配方(见下文"私有配方")

启用与禁用配方

[linux]、[macos]、[unix]、[windows] 是配置属性,默认所有配方总是启用;带有一个或多个配置属性的配方,只在对应配置激活时启用。这可以编写随操作系统行为不同的 justfile——以下 run 配方在 Unix 与 Windows 上使用不同的 C 编译器与二进制产物名:

[unix]
run:
  cc main.c
  ./a.out

[windows]
run:
  cl main.c
  main.exe

禁用变更目录

just 通常在执行配方时将当前目录设置为包含 justfile 的目录;[no-cd] 可禁用此行为,用于创建使用调用目录相对路径或对当前目录操作的配方:

[no-cd]
commit file:
  git add {{file}}
  git commit

反引号命令求值

反引号可用于存储命令的求值结果:

localhost := `dumpinterfaces | cut -d: -f2 | sed 's/\/.*//' | sed 's/ //g'`

serve:
  ./serve {{localhost}} 8080

缩进反引号(以三个反引号为界)会像缩进字符串一样去掉缩进:

# This backtick evaluates the command `echo foo\necho bar\n`, producing `foo\nbar\n`
stuff := ```
    echo foo
    echo bar
  ```

反引号内不能以 #! 开头(该语法为将来升级保留)。

条件表达式

if / else 表达式根据两个表达式是否相等评估不同分支:

foo := if "2" == "2" { "Good!" } else { "1984" }

bar:
  @echo "{{foo}}"
$ just bar
Good!

也支持不相等测试(!=)与正则匹配(=~):

foo := if "hello" =~ 'hel+o' { "match" } else { "mismatch" }

正则表达式由 Rust regex 包提供;由于正则常用反斜线转义,建议使用单引号字符串字面值。条件表达式是短路的——只评估一个分支,可确保反引号内的表达式在不应运行时不被执行:

foo := if env_var("RELEASE") == "true" { `get-something-from-release-database` } else { "dummy-value" }

条件语句也可用于配方内插值(注意最后的 } 后面必须有空格,否则插值被提前结束):

bar foo:
  echo {{ if foo == "bar" { "hello" } else { "goodbye" } }}

多个条件可以链式连接:

foo := if "hello" == "goodbye" {
  "xyz"
} else if "a" == "a" {
  "abc"
} else {
  "123"
}

用 error 停止执行

foo := if "hello" == "goodbye" {
  "xyz"
} else if "a" == "b" {
  "abc"
} else {
  error("123")
}

运行时产生错误 error: Call to function 'error' failed: 123,并附带源码位置。

从命令行设置变量

变量可以在命令行覆盖。任何数量的 NAME=VALUE 参数可以在配方前传递,或用 --set 标志:

os := "linux"

test: build
  ./test --test {{os}}

build:
  ./build {{os}}
$ just os=plan9
./build plan9
./test --test plan9

$ just --set os bsd
./build bsd
./test --test bsd

环境变量

导出 just 变量

以 export 关键字前缀的赋值将作为环境变量导出到配方:

export RUST_BACKTRACE := "1"

test:
  # 如果它崩溃了,将打印一个堆栈追踪
  cargo test

以 $ 为前缀的参数也会被导出:

test $RUST_BACKTRACE="1":
  cargo test

注意:导出的变量和参数不会被导出到同一作用域内反引号包裹的表达式里:

export WORLD := "world"
# This backtick will fail with "WORLD: unbound variable"
BAR := `echo hello $WORLD`

当 set export 被设置时,所有 just 变量都会作为环境变量导出。

从环境中获取环境变量

来自环境的环境变量会自动传递给配方:

print_home_folder:
  echo "HOME is: '${HOME}'"

从 .env 文件加载

设置 dotenv-load 后,just 会从 .env 文件加载环境变量(细节见上文"环境变量加载")。

配方参数

配方可以带参数:

build target:
  @echo 'Building {{target}}…'
  cd {{target}} && make
$ just build my-awesome-project
Building my-awesome-project…
cd my-awesome-project && make

向依赖传递参数

把依赖与参数放在括号里即可:

default: (build "main")

build target:
  @echo 'Building {{target}}…'
  cd {{target}} && make

变量也可作为参数传给依赖,且支持依赖间参数转发:

target := "main"

_build version:
  @echo 'Building {{version}}…'
  cd {{version}} && make

build: (_build target)

push target: (build target)
  @echo 'Pushing {{target}}…'

默认值

参数可以有默认值,默认值可以是任意表达式(字符串或路径拼接必须放在括号内):

default := 'all'

test target tests=default:
  @echo 'Testing {{target}}:{{tests}}…'
  ./test --tests {{tests}} {{target}}
$ just test server
Testing server:all…
$ just test server unit
Testing server:unit…
arch := "wasm"

test triple=(arch + "-unknown-unknown") input=(arch / "input.dat"):
  ./test {{triple}}

变长参数

最后一个参数可用 +(一个或多个)或 *(零个或多个)前缀声明变长,展开为空格分隔的字符串:

backup +FILES:
  scp {{FILES}} me@server.com:
$ just backup FAQ.md GRAMMAR.md
scp FAQ.md GRAMMAR.md me@server.com:
commit MESSAGE *FLAGS:
  git commit {{FLAGS}} -m "{{MESSAGE}}"

test +FLAGS='-q':
  cargo test {{FLAGS}}   # 变长参数可被命令行参数覆盖

引号与 $ 前缀参数

{{…}} 替换若含空格需要加引号,否则 Shell 会将其拆分:

search QUERY:
  lynx 'https://www.google.com/?q={{QUERY}}'

以 $ 为前缀的参数将作为环境变量导出:

foo $bar:
  echo $bar

用其他语言书写配方(Shebang 配方)

以 #! 开头的配方被称为 Shebang 配方:just 将配方主体保存到文件并运行它,从而可用任意语言编写配方:

polyglot: python js perl sh ruby nu

python:
  #!/usr/bin/env python3
  print('Hello from python!')

js:
  #!/usr/bin/env node
  console.log('Greetings from JavaScript!')

perl:
  #!/usr/bin/env perl
  print "Larry Wall says Hi!\n";

sh:
  #!/usr/bin/env sh
  hello='Yo'
  echo "$hello from a shell script!"

nu:
  #!/usr/bin/env nu
  let hello = 'Hola'
  echo $"($hello) from a nushell script!"

ruby:
  #!/usr/bin/env ruby
  puts "Hello from ruby!"

在 Unix 系操作系统(Linux、macOS)上,Shebang 配方的执行方式是:保存配方主体到临时目录的文件 → 标记可执行 → 执行;操作系统解析 Shebang 行并调用,例如 #!/usr/bin/env bash 最终会运行 /usr/bin/env bash /tmp/PATH_TO_SAVED_RECIPE_BODY 之类的命令。不同操作系统对 Shebang 行的分割方式不同。

Windows 不支持 Shebang 行;just 会自行将 Shebang 行分割成命令和参数,把配方主体保存到文件,并把文件路径作为最后一个参数调用。此外,在 Windows 上,包含 / 的解释器路径会先通过 cygpath(随 Cygwin 提供)从 Unix 风格路径转换为 Windows 风格路径;不含 / 的解释器路径则直接执行(适用于 cygpath 不可用或希望传递 Windows 风格路径的场景)。

更安全的 Bash Shebang 配方

建议在 bash Shebang 配方中加入 set -euxo pipefail:

foo:
  #!/usr/bin/env bash
  set -euxo pipefail
  hello='Yo'
  echo "$hello from Bash!"

其作用:set -e 命令失败即退出;set -u 变量未定义即退出;set -x 运行前打印每一行;set -o pipefail 管道中任一命令失败即退出(bash 特有,普通行式配方默认不开启)。

在配方中设置变量与共享环境

配方代码行由 Shell 解释,无法在配方中设置 just 变量;而每一行配方都由新的 Shell 实例运行,所以一行设置的 Shell 变量也不会在下一行生效:

foo:
  x=hello && echo $x # 这个没问题!
  y=bye
  echo $y            # 这个是有问题的, `y` 在此处未定义!

最佳解法是使用 Shebang 配方(整个配方体在同一个 Shell 实例中运行)。同理,配方间无法共享环境变量;对于需要激活环境的工具(如 Python venv),可改为直接执行虚拟环境二进制:

venv:
  [ -d foo ] || python3 -m venv foo

run: venv
  ./foo/bin/python3 main.py

改变配方中的工作目录

因为每行由新 Shell 执行,单独一行 cd bar 不会影响后续行;可用 cd bar && pwd 在同一行完成,或用 Shebang 配方。

缩进与多行结构

配方代码行可以用空格或制表符缩进,但不能混合使用;同一配方的所有行必须有相同缩进,不同配方可使用不同缩进。

没有 Shebang 的配方被逐行评估和运行,多行结构可能不按预期工作——例如 if 多行写法会产生 Recipe line has extra leading whitespace 解析错误。三种解决方案:单行书写、反斜线转义换行、使用 Shebang。

# if 语句:单行
conditional:
  if true; then echo 'True!'; fi

# if 语句:反斜线续行
conditional:
  if true; then \
    echo 'True!'; \
  fi

# if 语句:Shebang
conditional:
  #!/usr/bin/env sh
  if true; then
    echo 'True!'
  fi
# for 循环(单行 / 续行 / Shebang 三种写法)
for:
  for file in `ls .`; do echo $file; done

# while 循环
while:
  while `server-is-dead`; do ping -c 1 server; done

命令行选项

just 提供丰富的命令行选项用于列出、Dump 与调试配方和变量,完整列表可通过 just --help 查看:

$ just --list
Available recipes:
  js
  perl
  polyglot
  python
  ruby
$ just --show perl
perl:
  #!/usr/bin/env perl
  print "Larry Wall says Hi!\n";
$ just --show polyglot
polyglot: python js perl sh ruby

常用选项还包括:--summary(紧凑列出)、--evaluate(打印变量值)、--dump(转储 justfile,配合 --dump-format json --unstable 输出 JSON)、--completions(生成自动补全脚本)、--choose(交互式选择配方)、--changelog(打印更新日志)等。选项的解析实现在 src/subcommand.rs 中。

私有配方

名字以 _ 开头的配方和别名会在 just --list 与 just --summary 中被忽略(_test-helper 这类只作依赖的辅助配方):

test: _test-helper
  ./bin/test

_test-helper:
  ./bin/super-secret-test-helper-stuff

[private] 属性(1.10.0)无需改名即可隐藏配方(也适用于别名):

[private]
foo:

[private]
alias b := bar

bar:

源码中 src/recipe.rs 的 Recipe 结构体包含 private: bool 字段,并在 just --list 的过滤逻辑中跳过私有项(!self.private && !self.attributes.private())。

安静配方(Quiet Recipes)

配方名前加 @ 可反转每行行首 @ 的含义——默认安静、只有带 @ 的行才回显:

@quiet:
  echo hello
  echo goodbye
  @# all done!
$ just quiet
hello
goodbye
# all done!

Shebang 配方默认安静;在 Shebang 配方名称前加 @ 则会让 just 在执行前打印该配方:

@bar:
  #!/usr/bin/env bash
  echo 'Bar!'

just 在配方行失败时通常打印错误信息,可用 [no-exit-message](1.7.0)属性抑制——对包装外部工具的配方尤其有用:

[no-exit-message]
git *args:
    @git {{args}}

交互式选择器:--choose

--choose 子命令唤起一个选择器(从标准输入读取配方名、向标准输出打印选中的名称)来选择要运行的配方:

  • 目前无法通过 --choose 运行带参数的配方,因此这类配方不会列出;私有配方和别名也会被忽略。
  • 选择器可用 --chooser 覆写;未给出时依次检查 $JUST_CHOOSER,最后默认 fzf(参数可包含在选择器中,如 fzf --exact)。
  • 选择器的调用方式与配方行相同(如默认通过 sh -cu 'fzf' 调用,并尊重 Shell 覆写)。
default:
  @just --choose

其他目录下调用 justfile

如果传给 just 的第一个参数包含 /:在最后一个 / 处分割,之前部分视为搜索 justfile 的起始目录,之后部分视为正常参数(为空则忽略):

$ (cd foo && just build)
$ just foo/build
$ just foo/

三者等价。这适用于在包含子目录 foo(内含带默认配方 build 的 justfile)的目录中运行命令。

隐藏 justfile 与 Just 脚本

just 同时寻找 justfile 与 .justfile,因此可以使用隐藏的 justfile。

通过在 justfile 顶部添加 Shebang 行并使其可执行,just 还可以作为脚本的解释器:

$ cat > script <<EOF
#!/usr/bin/env just --justfile

foo:
  echo foo
EOF
$ chmod +x script
$ ./script foo
echo foo
foo

系统会把脚本路径作为 Shebang 命令的参数(最终命令形如 /usr/bin/env just --justfile PATH_TO_SCRIPT)。上面的写法会把工作目录改为脚本位置;想保持工作目录不变可用 #!/usr/bin/env just --working-directory . --justfile。注意 Shebang 行分隔在不同操作系统上并不一致——Linux 上可能需要给 env 传 -S 标志:

#!/usr/bin/env -S just --justfile

default:
  echo foo

将 justfile 转为 JSON

--dump 搭配 --dump-format json 可以打印 justfile 的 JSON 表示;该格式尚不稳定,需要 --unstable 标志。对应的测试见 tests/json.rs。

回退到父 justfile(fallback)

设置 fallback 后,若当前 justfile 中没有找到配方,just 会向父目录逐级搜索 justfile,遇到其中 fallback 为 false 或未设置的 justfile 时停止:

# 当前目录 justfile
set fallback
foo:
  echo foo
# 父目录 justfile
bar:
  echo bar
$ just --unstable bar
Trying ../justfile
echo bar
bar

避免参数分割

考虑 just foo "some argument.txt":用户 Shell 会把 "some argument.txt" 解析为一个参数,但当 just 把 touch {{argument}} 替换为 touch some argument.txt 时引号未保留,touch 会收到两个参数、创建两个文件。有三种规避方式:

  • 引号包裹:touch '{{argument}}'——保留 just 在运行前捕捉变量名拼写错误的能力,但参数值含单引号时不适用;
  • 位置参数:set positional-arguments 后使用 touch "$1"——对所有值(含双引号)有效,但失去拼写错误检查(如误写 $2 不会报错);
  • 导出参数:set export 后 touch "$argument",或单参数导出 foo $argument: 后 touch "$argument"——同样对所有值有效但失去拼写检查。

多任务并行与配套工具

parallel:
  #!/usr/bin/env -S parallel --shebang --ungroup --jobs {{ num_cpus() }}
  echo task 1 start; sleep 3; echo task 1 done
  echo task 2 start; sleep 3; echo task 2 done
  echo task 3 start; sleep 3; echo task 3 done
  echo task 4 start; sleep 3; echo task 4 done
  • Shell 别名:alias j=just 快速运行;bash 中别名可能不保留自动补全,可在 .bashrc 添加 complete -F _just -o bashdefault -o default j。

Shell 自动补全

Bash、Zsh、Fish、PowerShell、Elvish、Nushell 的补全脚本已收录在 completions/ 目录(对应 just.bash、just.zsh、just.fish、just.powershell、just.elvish、just.nu)。just 二进制运行时也可生成相同脚本:

$ just --completions zsh > just.zsh

macOS 注意:若通过 Homebrew 安装 just,它会把 zsh 补全脚本安装到 Homebrew 的 zsh 目录;可在 .zshrc 中于调用 compinit 之前设置 fpath=($HOMEBREW_PREFIX/share/zsh/site-functions $fpath)。

全局用户 justfile

若希望某些配方随处可用,可在 ~/.user.justfile 中定义配方:

# 配方别名:为每个配方创建 Shell 别名
for recipe in `just --justfile ~/.user.justfile --summary`; do
  alias $recipe="just --justfile ~/.user.justfile --working-directory . $recipe"
done

# 别名转发:不逐配方建别名
alias .j='just --justfile ~/.user.justfile --working-directory .'

也可定制工作目录,例如在 ~ 中运行配方:alias .j='just --justfile ~/.user.justfile --working-directory ~'。

Node.js package.json 脚本兼容

以下导出语句使 just 配方能够访问本地 Node 模块二进制文件,行为更接近 package.json 中的 script 条目:

export PATH := "./node_modules/.bin:" + env_var('PATH')

语法与源码资料

  • justfile 的非正式语法说明见 GRAMMAR.md。
  • 更新日志见 CHANGELOG.md,或运行 just --changelog。
  • 历史遗留的 Shell 版本(名为 make)见 contrib/just.sh。
  • 本项目自身的 justfile(justfile)可作为真实世界的最佳实践参考。

常见问题

just 与 Cargo 构建脚本的关系

cargo 构建脚本有特定用途(控制 cargo 如何构建 Rust 项目,如给 rustc 添加标志、构建外部依赖、运行 codegen 步骤);just 则用于开发中所有其他杂项命令——不同配置下运行测试、代码检查、推送构建产物、清理临时文件等。尽管 just 用 Rust 编写,它适用于任何语言或项目。

向后兼容性承诺

随着 1.0 发布,just 承诺向后兼容:未来版本不会引入破坏现有 justfile 或 CLI 调用的不兼容变更;不排除修复全面错误;"永远不会有一个 just 2.0",理想的向后兼容变更会按 justfile 逐个选择性加入;尚未稳定的功能由 --unstable 标志选择性启用,且随时可能不兼容地变化。仓库 CHANGELOG.md 记录了每次发布的演进细节。

结语:为每个项目写一个 justfile

无论项目大小,把测试、构建、检查、部署、复杂的 git 工作流、依赖更新、多组测试等命令集中写入 justfile,都能显著降低团队沟通成本与记忆负担;即使个人项目,通过名字而非 Shell 历史反查来运行命令也是巨大福音。just 是命令运行器领域的成熟选择:它既有 make 启发的易用语法,又通过静态错误检测、参数化配方、dotenv 注入、跨平台 Shell 配置与源码级可测试性,成为现代开发工作流中可靠的一环。

登录后查看全文
just