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']);
The same applies when using the template string syntax. However, spaces, tabs and newlines must use ${}
.
await execa`npm run ${'task with space'}`;
The above syntaxes allow the file and its arguments to be user-defined by passing a variable.
const command = 'npm';
const commandArguments = ['run', 'task with space'];
await execa(command, commandArguments);
await execa`${command} ${commandArguments}`;
However, execaCommand()
must be used instead if:
- Both the file and its arguments are user-defined
- And those are supplied as a single string
This is only intended for very specific cases, such as a REPL. This should be avoided otherwise.
import {execaCommand} from 'execa';
for await (const commandAndArguments of getReplLine()) {
await execaCommand(commandAndArguments);
}
Arguments passed to execaCommand()
are automatically escaped. They can contain any character (except null bytes), but spaces must be escaped with a backslash.
await execaCommand('npm run task\\ with\\ space');
Shells (Bash, cmd.exe, etc.) are not used unless the shell
option is set. This means shell-specific characters and expressions ($variable
, &&
, ||
, ;
, |
, etc.) have no special meaning and do not need to be escaped.
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.
$`ssh host ${'npm run "task with space"'}`;
Next: 💻 Shell
Previous: ️
Top: Table of contents