What is shell-escape?
The shell-escape npm package is used to escape and sanitize strings for use in shell commands. This is particularly useful to prevent shell injection attacks and ensure that shell commands are executed safely.
What are shell-escape's main functionalities?
Basic String Escaping
This feature allows you to escape a basic string to be safely used in a shell command. The example demonstrates escaping a simple echo command.
const shellEscape = require('shell-escape');
const command = shellEscape(['echo', 'Hello World']);
console.log(command); // Output: echo 'Hello World'
Escaping Arguments with Special Characters
This feature shows how to escape arguments that contain special characters. The example demonstrates escaping a string with an ampersand.
const shellEscape = require('shell-escape');
const command = shellEscape(['echo', 'Hello & World']);
console.log(command); // Output: echo 'Hello & World'
Escaping File Paths
This feature allows you to escape file paths that may contain spaces or other special characters. The example demonstrates escaping a file path with spaces.
const shellEscape = require('shell-escape');
const filePath = '/path/to/some file.txt';
const command = shellEscape(['cat', filePath]);
console.log(command); // Output: cat '/path/to/some file.txt'
Other packages similar to shell-escape
shell-quote
The shell-quote package provides similar functionality to shell-escape, allowing you to escape and quote strings for use in shell commands. It also offers additional features like parsing shell commands into arguments. Compared to shell-escape, shell-quote provides more comprehensive parsing and quoting capabilities.
shescape
The shescape package is another alternative for escaping strings for shell commands. It focuses on providing a simple and effective way to escape strings, similar to shell-escape. However, it may not have as many features as shell-quote.
shell-escape
Escape and stringify an array of arguments to be executed on the shell
Install
npm install shell-escape
Example
simple
var shellescape = require('shell-escape');
var args = ['curl', '-v', '-H', 'Location;', '-H', 'User-Agent: dave#10', 'http://www.daveeddy.com/?name=dave&age=24'];
var escaped = shellescape(args);
console.log(escaped);
yields
curl -v -H 'Location;' -H 'User-Agent: dave#10' 'http://www.daveeddy.com/?name=dave&age=24'
A command suitable for being executed by the shell
advanced
var shellescape = require('shell-escape');
var args = ['echo', 'hello!', 'how are you doing $USER', '"double"', "'single'"];
var escaped = shellescape(args);
console.log(escaped);
yields
echo 'hello!' 'how are you doing $USER' '"double"' \''single'\'
and when run on the shell
$ echo 'hello!' 'how are you doing $USER' '"double"' \''single'\'
hello! how are you doing $USER "double" 'single'
License
MIT