Created
April 26, 2012 20:08
-
-
Save creationix/2502704 to your computer and use it in GitHub Desktop.
Bash argument escaping
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Implement bash string escaping. | |
var safePattern = /^[a-z0-9_\/\-.,?:@#%^+=\[\]]*$/i; | |
var safeishPattern = /^[a-z0-9_\/\-.,?:@#%^+=\[\]{}|&()<>; *']*$/i; | |
function bashEscape(arg) { | |
// These don't need quoting | |
if (safePattern.test(arg)) return arg; | |
// These are fine wrapped in double quotes using weak escaping. | |
if (safeishPattern.test(arg)) return '"' + arg + '"'; | |
// Otherwise use strong escaping with single quotes | |
return "'" + arg.replace(/'+/g, function (val) { | |
// But we need to interpolate single quotes efficiently | |
// One or two can simply be '\'' -> ' or '\'\'' -> '' | |
if (val.length < 3) return "'" + val.replace(/'/g, "\\'") + "'"; | |
// But more in a row, it's better to wrap in double quotes '"'''''"' -> ''''' | |
return "'\"" + val + "\"'"; | |
}) + "'"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@kriskowal Right on... I thought I knew sh/bash OK, but I'm finding surprises in playing with this. Bash is wacky... which begs the question, why are we still using it? It really should be deprecated in favor of A) a very simple interactive shell and B) a real language for serious scripting (Nodejs is great :-)
@creationix Speaking of context, you should add a usage example... I think I know what you're up to, and it's dead simple, but...