Escape Bash, PowerShell, CMD and mixed shell CLI commands.
Note that this package is in early stages of development and there may be breaking changes within semantically compatible versions. See change log.
With yarn:
yarn add shell-encode
Or with npm:
npm install --save shell-encode
Has no dependencies. TypeScript types defined.
const shellEncode = require('shell-encode');
ES6 syntax:
import shellEncode from 'shell-encode';
The method shellEncode()
, encodes a CLI command specified as arguments.
The result is ready to use as a CLI command for the specified shell.
The default shell is bash, but can be changed.
var cmd = shellEncode('echo', ['Hello "World"!']);
console.log(cmd);
// Output: echo 'Hello "World"!'
To change the shell, add an options object as the last argument.
For example:
var cmd = shellEncode('echo', ['Hello "World"!'], { shell: 'cmd' });
console.log(cmd);
// Output: echo Hello^ \"World\"^!
Specifiying an array instead of a string combines the contents of the array into a single string argument. This is usefull when you want to pass nested arguments.
For example:
// cmd.run with testscript2, which has its own arguments:
var cmd = shellEncode('cmd.run', ['./testscript2', ['arg1', 'arg2']]);
console.log(cmd);
// Output: cmd.run "./testscript2 'arg1 arg2'"
You may want to call another shell from within a command. Specify the nested shell options as the last argument or item of the argument array.
For example:
// Call PowerShell from within CMD:
var cmd = shellEncode(
'powershell', [
'Write-Output', ['Hello World!'], { shell: 'powershell' }
], { shell: 'cmd' });
console.log(cmd);
// Output: powershell Write-Output^ 'Hello^ World^!'
Also have a look at the examples folder.
shellEncode.setDefaults('powershell');
- Multiple lines are merged into a single line.
- You need to wrap each pipe in an array as CMD escapes the line multiple times. For example, if there is a single pipe, CMD will escape commands before the pipe once and will escape commands after the pipe twice.
- Multiple lines are merged into a single line.