开始使用
概述
#!/usr/bin/env zx
await $`cat package.on | grep name`
const branch = await $`git branch --show-current`
await $`dep deploy --branch=${branch}`
await Promise.all([
$`sleep 1; echo 1`,
$`sleep 2; echo 2`,
$`sleep 3; echo 3`,
])
const name = 'foo bar'
await $`mkdir /tmp/${name}`Bash 很棒,但当编写更复杂的脚本时,许多人更喜欢更方便的编程语言。 JavaScript 是一个完美的选择,但 Node. 标准库在使用前需要额外的麻烦。 zx 包提供了围绕 child_process 的有用包装器,转义参数并提供合理的默认值。
安装
npm install zx或许多其他方法
用法
以 .m 扩展名将脚本写入文件,以便在顶层使用 await。 如果您更喜欢 . 扩展名,请将您的脚本包装在类似 void async function () {...}() 的东西中。
将以下 shebang 添加到您的 zx 脚本的开头
#!/usr/bin/env zx现在您将能够像这样运行您的脚本
chmod +x ./script.m
./script.m或通过 CLI
zx ./script.m所有函数($、cd、fetch 等)都可以直接使用,无需任何导入。
或显式导入全局变量(以便在 VS Code 中获得更好的自动完成功能)。
import 'zx/globals'$`command`
使用 spawn 函数执行给定的命令,并返回 ProcessPromise。 它支持同步和异步模式。
const list = await $`ls -la`
const dir = $.sync`pwd`所有通过 ${...} 传递的内容都将自动转义并用引号引起来。
const name = 'foo & bar'
await $`mkdir ${name}`无需添加额外的引号。 在引号中阅读更多相关信息。
如果需要,您可以传递一个参数数组
const flags = [
'--oneline',
'--decorate',
'--color',
]
await $`git log ${flags}`如果执行的程序返回非零退出代码,则会抛出 ProcessOutput。
try {
await $`exit 1`
} catch (p) {
console.log(`Exit code: ${p.exitCode}`)
console.log(`Error: ${p.stderr}`)
}ProcessOutput
class ProcessOutput {
readonly stdout: string
readonly stderr: string
readonly signal: string
readonly exitCode: number
toString(): string // Combined stdout & stderr.
}进程的输出按原样捕获。 通常,程序在末尾打印一个新行 \n。 如果 ProcessOutput 用作某些其他 $ 进程的参数,zx 将使用 stdout 并修剪新行。
const date = await $`date`
await $`echo Current date is ${date}.`许可证
免责声明:这不是 Google 官方支持的产品。