Appearance
引号
¥Quotes
Bash 支持多种引用参数的方式:单引号、双引号和使用 C 样式引号的 bash 特定方法 $'...'
。Zx 更喜欢后一种方法。
¥Bash supports various ways to quote arguments: single quotes, double quotes, and a bash-specific method using C-style quotes $'...'
. Zx prefers the latter approach.
js
const name = 'foo & bar'
await $`mkdir ${name}`
Zx 自动转义并引用 ${...}
内的任何内容,因此不需要额外的引号。
¥Zx automatically escapes and quotes anything within ${...}
, so there's no need for additional quotes.
以下示例产生相同的正确结果:
¥The following examples produce the same, correct result:
js
await $`mkdir ${'path/to-dir/' + name}`
js
await $`mkdir path/to-dir/${name}`
请记住,PowerShell
或 pwsh
需要相应的引用实现。定义 通过助手 或手动:
¥Keep in mind, that PowerShell
or pwsh
requires a corresponding quote implementation. Define it via helpers or manually:
js
import { quotePowerShell } from 'zx'
$.quote = quotePowerShell
参数数组
¥Array of arguments
Zx 还可以接受 ${...}
内的参数数组。每个数组项将单独引用,然后用空格连接。
¥Zx can also accept an array of arguments within ${...}
. Each array item will be quoted separately and then joined by a space.
js
const flags = [
'--oneline',
'--decorate',
'--color',
]
await $`git log ${flags}`
通配符模式
¥Glob patterns
因为 Zx 转义了 ${...}
内的所有内容,所以不能直接使用 glob 语法。相反,Zx 提供了 glob
功能。
¥Because Zx escapes everything inside ${...}
, you can't use glob syntax directly. Instead, Zx provides a glob
function.
以下示例将不起作用:
¥The following example won't work:
js
const files = './**/*.md'// Incorrect
await $`ls ${files}`
正确的做法:
¥The correct approach:
js
const files = await glob('./**/*.md')
await $`ls ${files}`
主目录 ~
¥Home dir ~
如果主目录符号 ~
在 ${...}
内,Zx 不会扩展它。为此目的使用 os.homedir()
。
¥Zx won't expand the home directory symbol ~
if it's within ${...}
. Use os.homedir()
for that purpose.
js
const dir = `~/Downloads`// Incorrect
await $`ls ${dir}`
js
await $`ls ${os.homedir()}/Downloads` // Correct
js
await $`ls ~/Downloads` // Correct, ~ is outside of ${...}
组装命令
¥Assembling commands
如果你尝试在 Zx 中动态组合命令,你可能会遇到限制。例如,以下方法将不起作用:
¥If you're trying to dynamically assemble commands in Zx, you might run into limitations. For instance, the following approach won't work:
js
const cmd = 'rm'
if (force) cmd += ' -f'
if (recursive) cmd += ' -r'
cmd += ' ' + file
await $`${cmd}`// Incorrect
Zx 将对整个字符串进行转义,使命令无效。相反,组装一个参数数组并将其传递给 Zx,如下所示:
¥Zx will escape the entire string, making the command invalid. Instead, assemble an array of arguments and pass it to Zx like this:
js
const args = []
if (force) args.push('-f')
if (recursive) args.push('-r')
args.push(file)
await $`rm ${args}`