๐ฌ Escaping/quoting
May 25, 2024 ยท View on GitHub
๐ฌ Escaping/quoting
Array syntax
When using the array syntax, arguments are automatically escaped. They can contain any character, including spaces, tabs and newlines. However, they cannot contain null bytes: binary inputs should be used instead.
import {execa} from 'execa';
await execa('npm', ['run', 'task with space']);
Template string syntax
The same applies when using the template string syntax. However, spaces, tabs and newlines must use ${}.
await execa`npm run ${'task with space'}`;
User-defined input
The above syntaxes allow the file and its arguments to be user-defined by passing a variable.
import {execa} from 'execa';
const file = 'npm';
const commandArguments = ['run', 'task with space'];
await execa`${file} ${commandArguments}`;
await execa(file, commandArguments);
If the file and/or multiple arguments are supplied as a single string, parseCommandString() can split it into an array.
import {execa, parseCommandString} from 'execa';
const commandString = 'npm run task';
const commandArray = parseCommandString(commandString);
await execa`${commandArray}`;
const [file, ...commandArguments] = commandArray;
await execa(file, commandArguments);
Spaces are used as delimiters. They can be escaped with a backslash.
await execa`${parseCommandString('npm run task\\ with\\ space')}`;
Shells
Shells (Bash, cmd.exe, etc.) are not used unless the shell option is set. This means shell-specific syntax has no special meaning and does not need to be escaped:
- Quotes:
"value",'value',$'value' - Characters:
$variable,&&,||,;,| - Globbing:
*,** - Expressions:
$?,~
// This prints `$TASK_NAME`, not `build`
await execa({env: {TASK_NAME: 'build'}})`echo $TASK_NAME`;
If you do set the shell option, arguments will not be automatically escaped anymore. Instead, they will be concatenated as a single string using spaces as delimiters.
await execa({shell: true})`npm ${'run'} ${'task with space'}`;
// Is the same as:
await execa({shell: true})`npm run task with space`;
Therefore, you need to manually quote the arguments, using the shell-specific syntax.
await execa({shell: true})`npm ${'run'} ${'"task with space"'}`;
// Is the same as:
await execa({shell: true})`npm run "task with space"`;
Sometimes a shell command is passed as argument to an executable that runs it indirectly. In that case, that shell command must quote its own arguments.
const command = 'npm run "task with space"';
await execa`ssh host ${command}`;
Next: ๐ป Shell
Previous: ๏ธโถ๏ธ Basic execution
Top: Table of contents