From 98e7de76c55c79d72429b2cb62809abbdb23597a Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Thu, 19 Aug 2021 23:40:20 +0200 Subject: [PATCH] Add docs about quoting --- README.md | 20 ++++++++++++-- docs/quotes.md | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 2 deletions(-) create mode 100644 docs/quotes.md diff --git a/README.md b/README.md index aad5a3f4e0..85790a2242 100644 --- a/README.md +++ b/README.md @@ -66,9 +66,25 @@ without any imports. Executes a given string using the `spawn` function from the `child_process` package and returns `ProcessPromise`. +Everything passed through `${...}` will be automatically escaped and quoted. + +```js +let name = 'foo & bar' +await $`mkdir ${name}` +``` + +There is no need to add extra quotes. Read more about it in +[quotes](docs/quotes.md). + +You can pass an array of arguments if needed: + ```js -let count = parseInt(await $`ls -1 | wc -l`) -console.log(`Files count: ${count}`) +let flags = [ + '--oneline', + '--decorate', + '--color', +] +await $`git log ${flags}` ``` For example, to upload files in parallel: diff --git a/docs/quotes.md b/docs/quotes.md new file mode 100644 index 0000000000..c98df1fc7b --- /dev/null +++ b/docs/quotes.md @@ -0,0 +1,73 @@ +# Quotes + +When passing arguments to `${...}` there is no need to add quotes. **Quotes will +be added automatically if needed.** + +```js +let name = 'foo & bar' +await $`mkdir ${name}` +``` + +For quotes **zx** uses special bash syntax (next commands are valid bash): + +```bash +mkdir $'foo & bar' +$'ls' $'-la' +``` + +If you add quotes `"${name}"`, it will produce a wrong command. + +If you need to add something extra, consider putting it inside curly brackets. + +```js +await $`mkdir ${'path/to-dir/' + name}` +``` + +This will also work properly: + +```js +await $`mkdir path/to-dir/${name}` +``` + +### Array of arguments + +The `zx` can also take an array or arguments in the `${...}`. Items of the array +will be quoted separately and concatenated via a space. Do **not** add a `.join(' ')`. + +```js +let flags = [ + '--oneline', + '--decorate', + '--color', +] +await $`git log ${flags}` +``` + +If you already have a string with arrays, it's your responsibility +to correctly parse it and distinguish separate arguments. For example like this: + +```js +await $`git log ${'--oneline --decorate --color'.split(' ')}` +``` + +### globbing and `~` + +As everything passed through `${...}` will be escaped, you can't use `~` +or glob syntax. In order for this to work the zx provides +[globby package](../README.md#globby-package). + +For instead of this: + +```js +let files = '~/dev/**/*.md' +await $`ls ${files}` +``` + +Use `glob` function and `os` package: + +```js +let files = await glob(os.homedir() + '/dev/**/*.md') +await $`ls ${files}` +``` + +