Zx — 使用 JavaScript 撰寫更優質的 Shell 腳本
概覽
zx 是 Google 推出的工具,讓你能用 JavaScript/TypeScript 來撰寫 Shell 腳本。它包裝了 child_process,自動跳脫引數,並提供合理的預設值 —— 讓你在腳本中也能擁有 JavaScript 生態系的威力。
#!/usr/bin/env zx
await $`cat package.json | grep name`
const branch = await $`git branch --show-current`
await $`dep deploy --branch=${branch}`
const name = 'foo & bar'
await $`mkdir /tmp/${name}` // 無需引號 — 自動跳脫
Bash 對於簡單任務來說很棒,但當腳本變得複雜時,一個完整的程式語言會更有幫助。zx 在 child_process 周圍添加了有用的包裝器,會自動跳脫引數,並提供合理的預設值。想像一下:bash + JavaScript 融合在一個腳本中。
觸發時機
當使用者詢問有關從 JavaScript 執行 Shell 命令、將 Bash 腳本轉換為 zx、執行遠端腳本、Markdown 腳本或 TypeScript Shell 腳本時,也會觸發此技能。
快速開始
npm install zx
將腳本寫成 .mjs 檔案(支援頂層 await)。加入 #!/usr/bin/env zx shebang 或透過 CLI 執行:
zx ./script.mjs # 直接執行
npx zx ./script.mjs # 透過 npx
node --import zx/globals # 作為 Node.js 載入器
所有函式($, cd, fetch 等)在 zx 腳本中都是全域可用的,無需匯入。若要進行明確導入(以獲得更好的 VS Code 自動完成):
import 'zx/globals'
核心概念
$`command` — 執行 Shell 命令
標籤樣板字面值是 zx 的核心。${...} 內的所有內容都會被自動跳脫並加上引號。
// 非同步(標準)— 回傳 ProcessPromise
const output = await $`ls -la`
// 同步變體 — 直接回傳 ProcessOutput
const dir = $.sync`pwd`
// 陣列會被扁平化
const flags = ['--oneline', '--decorate', '--color']
await $`git log ${flags}`
// 非零退出碼會拋出 ProcessOutput
try {
await $`exit 1`
} catch (p) {
console.log(`Exit: ${p.exitCode}, Error: ${p.stderr}`)
}
使用 $({...}) 進行預設配置
建立具有預設選項的自訂 $ 實例 — 可鏈結且可組合:
const $$ = $({ verbose: false, env: { NODE_ENV: 'production' } })
const pwd = $$.sync`pwd`
// 預設值可鏈結
const $1 = $({ nothrow: true })
const $2 = $1({ sync: true }) // 同時套用 nothrow + sync
ProcessPromise 與 ProcessOutput
$`cmd` ProcessPromise (繼承 Promise)
├── .pipe() 串流管線
├── .kill() 終止程序
├── .text() 以字串形式輸出
├── .json() 以解析後的 JSON 形式輸出
├── .lines() 輸出按行分割
├── .nothrow() 為此命令壓制錯誤
├── .quiet() 為此命令壓制輸出
├── .timeout() 在指定時間後自動終止
├── .stdio() 配置 I/O
├── .exitCode Promise<退出碼>
├── .stdout 可讀取串流
├── .stderr 可讀取串流
├── .stdin 可寫入串流
├── .pid / .cmd 程序元資料
└── await → ProcessOutput
├── .stdout string
├── .stderr string
├── .exitCode number
├── .signal string|null
├── .text() / .json() / .lines() / .buffer() / .blob()
└── .ok boolean (使用 nothrow 時)
決策樹
在編寫 zx 腳本時,請使用此決策樹:
| 目標 | 方法 |
|---|---|
| 執行命令 | await $`cmd` |
| 同步執行 | $.sync`cmd` |
| 管線輸出 | .pipe($`next`) / .pipe('file.txt') |
| 優雅地處理錯誤 | $({nothrow: true}) / .nothrow() |
| 設定超時 | $({timeout: '30s'}) / .timeout('30s') |
| 解析 JSON 輸出 | (await $`cmd`).json() |
| 即時串流 | for await (const line of $`cmd`) |
| 失敗時重試 | retry(5, () => $`cmd`) |
| 使用者提示 | question('Name: ') |
| 進度指示器 | await spinner('Working...', () => $`cmd`) |
| 切換目錄 | cd('/path') 或 within(() => { $.cwd = '/tmp' }) |
| 暫存檔/目錄 | tmpfile() / tmpdir() |
| 解析 CLI 引數 | argv.flag 或 minimist(process.argv.slice(2)) |
| 載入 .env 檔案 | dotenv.config('.env') |
撰寫有效的 zx 腳本
平行執行
const results = await Promise.all([
$`sleep 1; echo 1`,
$`sleep 2; echo 2`,
$`sleep 3; echo 3`,
])
使用 nothrow 進行錯誤處理
$.nothrow = true
const repos = ['zx', 'webpod']
const clones = repos.map(n => $`git clone https://github.com/google/${n}`)
const results = await Promise.all(clones)
const errors = results.filter(o => !o.ok).map(o => o.stderr.trim())
console.log('Errors:', errors.join('\n'))
串流管線
// 像 Bash 管道一樣鏈結命令
const greeting = await $`printf "hello"`
.pipe($`awk '{printf $1", world!"}'`)
.pipe($`tr '[a-z]' '[A-Z]'`)
// 管線到檔案
await $`echo "Hello!"`.pipe('/tmp/output.txt')
// 即時輸出到終端
await $`echo 1; sleep 1; echo 2; sleep 1; echo 3`.pipe(process.stdout)
串流分割與合併
// 將一個來源分割到多個消費者
const p = $`some-command`
const [o1, o2] = await Promise.all([
p.pipe`log`,
p.pipe`extract`,
])
// 合併多個來源
const $h = $({ halt: true })
const p1 = $`echo foo`
const p2 = $h`echo a && sleep 0.1 && echo b`
const p3 = $h`echo c && sleep 0.1 && echo d`
const cat = $h`cat`
p1.pipe(cat); p2.pipe(cat); p3.pipe(cat)
await cat.run()
輸出格式化器
const p = $`echo '{"foo":"bar"}\nline2'`
await p.json() // { foo: 'bar' }
await p.lines() // ['{"foo":"bar"}', 'line2']
await p.text() // '{"foo":"bar"}\nline2\n'
異步迭代
for await (const line of $`git log --oneline --max-count=5`) {
console.log(line)
}
Shell 配置
zx 預設使用 bash。如有需要可切換 Shell:
import { useBash, usePowerShell, usePwsh } from 'zx'
usePowerShell() // PowerShell.exe
usePwsh() // PowerShell v7+
useBash() // 回到 bash
// 手動覆寫
$.shell = '/bin/zsh'
在 Windows 上,考慮使用 WSL 或 Git Bash 來提供 bash 支援,或透過 usePowerShell() 切換到 PowerShell。
內建輔助函式摘要
| 輔助函式 | 用途 | 範例 |
|---|---|---|
cd() | 切換目錄 | cd('/tmp') |
fetch() | HTTP 請求,支援 .pipe() | fetch('https://api.example.com') |
question() | 互動式使用者輸入 | question('Name: ') |
sleep() | 延遲執行 | await sleep(1000) |
echo() | 輸出到 stdout | echo`Status: ${p}` |
stdin() | 讀取 stdin | JSON.parse(await stdin()) |
within() | 隔離的非同步配置上下文 | within(() => { $.cwd = '/tmp' }) |
retry() | 帶延遲/退讓的重試 | retry(5, () => $curl url) |
spinner() | CLI 進度指示器 | await spinner(() => $long-cmd) |
glob() | 檔案 Glob 模式匹配 (globby) | glob('**/*.js') |
which() | 尋找可執行檔路徑 | await which('node') |
ps | 跨平台程序列表 | ps.lookup({ command: 'node' }) |
tmpdir() | 暫存目錄 | tmpdir('sub') |
tmpfile() | 暫存檔 | tmpfile('f.txt', 'content') |
argv | 解析後的 CLI 引數 | argv.verbose |
dotenv | .env 檔案載入 | dotenv.config('.env') |
已暴露的 npm 套件: chalk (顏色), fs (fs-extra), os, path, YAML (yaml), minimist.
資源
- references/api.md — 完整 API 參考:
$選項、cd()、fetch()、question()、sleep()、echo()、stdin()、within()、retry()、spinner()、glob()、which()、ps、kill()、tmpdir()、tmpfile()、minimist、argv、chalk、fs、os、path、YAML、dotenv、quote()、useBash()、usePowerShell()、usePwsh() - references/configuration.md — 所有
$.options:shell、prefix、postfix、quote、verbose、quiet、env、cwd、timeout、nothrow、detached、preferLocal、spawn、kill、log、input、signal、stdio、halt、delimiter、defaults - references/cli.md — CLI 使用方式:旗標、環境變數、Markdown 腳本、遠端腳本、stdin 執行、REPL 模式
- references/process.md — ProcessPromise/ProcessOutput 生命週期、管線、終止、中止、輸出格式化器、串流處理