引号
Bash 支持多种引用参数的方法:单引号、双引号以及使用 C 风格引号 $'...'
的 bash 特有方法。 Zx 更喜欢后一种方法。
js
const name = 'foo & bar'
await $`mkdir ${name}`
警告
Zx 会自动转义和引用 ${...}
中的任何内容,因此无需额外的引号。 此外,这可能会导致**不安全的注入**。
ts
const args = ['param && echo bar']
const p = $`echo --foo=$'${args}'`
(await p).stdout // '--foo=$param\nbar\n'
以下示例产生相同且正确的结果
js
await $`mkdir ${'path/to-dir/' + name}`
js
await $`mkdir path/to-dir/${name}`
请记住,PowerShell
或 pwsh
需要相应的引号实现。 通过助手或手动定义它
js
import { quotePowerShell } from 'zx'
$.quote = quotePowerShell
参数数组
Zx 还可以接受 ${...}
中的参数数组。 每个数组项将被单独引用,然后用空格连接。
js
const flags = [
'--oneline',
'--decorate',
'--color',
]
await $`git log ${flags}`
Glob 模式
由于 Zx 会转义 ${...}
中的所有内容,因此您无法直接使用 glob 语法。 相反,Zx 提供了一个 glob
函数。
以下示例不起作用
js
const files = './**/*.md' // [!code error] // Incorrect
await $`ls ${files}`
正确的方法
js
const files = await glob('./**/*.md')
await $`ls ${files}`
Home 目录 ~
如果 home 目录符号 ~
位于 ${...}
中,Zx 将不会展开它。为此目的,请使用 os.homedir()
。
js
const dir = `~/Downloads` // [!code error] // Incorrect
await $`ls ${dir}`
js
await $`ls ${os.homedir()}/Downloads` // Correct
js
await $`ls ~/Downloads` // Correct, ~ is outside of ${...}
组装命令
如果您尝试在 Zx 中动态组装命令,您可能会遇到限制。 例如,以下方法不起作用
js
const cmd = 'rm'
if (force) cmd += ' -f'
if (recursive) cmd += ' -r'
cmd += ' ' + file
await $`${cmd}` // [!code error] // Incorrect
Zx 将转义整个字符串,导致命令无效。 相反,组装一个参数数组并像这样将其传递给 Zx
js
const args = []
if (force) args.push('-f')
if (recursive) args.push('-r')
args.push(file)
await $`rm ${args}`