shell-encode

Escape Bash, PowerShell, CMD and mixed shell CLI commands.

Usage no npm install needed!

<script type="module">
  import shellEncode from 'https://cdn.skypack.dev/shell-encode';
</script>

README

shell-encode

Escape Bash, PowerShell, CMD and mixed shell CLI commands.

Node.js CI License: MIT Run on Repl.it

Note that this package is in early stages of development and there may be breaking changes within semantically compatible versions. See change log.

Installation

With yarn:

yarn add shell-encode

Or with npm:

npm install --save shell-encode

Has no dependencies. TypeScript types defined.

Usage

Import:

const shellEncode = require('shell-encode');

ES6 syntax:

import shellEncode from 'shell-encode';

Basic Usage:

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\"^!

Nested Arguments

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'"

Cross-Shell Encoding

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.

Changing the Default Shell

shellEncode.setDefaults('powershell');

Shell Specific Notes

CMD

  • 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.

PowerShell

  • Multiple lines are merged into a single line.