Created
January 22, 2011 00:46
-
-
Save thepaul/790722 to your computer and use it in GitHub Desktop.
escape random strings to make them single words in shells
This file contains 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
import re | |
backslash_shell_quote_re = re.compile(r'([^A-Za-z0-9_.,:/])') | |
def shell_escape(s, flavor='sh'): | |
""" | |
Escape a random string (s) so that it reads as a single word when | |
undergoing shell command-line parsing. | |
The default flavor should be safe for all mainstream shells I know | |
about, but there are some other escaping modes which may result in | |
more compact or more readable output. | |
Available flavors: | |
bash, zsh: use dollar-quoting ($'foo') | |
sh, csh: use standard single-quotes except when quoting single- | |
quote characters | |
backslash: use no quotes; escape all unsafe characters with a | |
backslash | |
""" | |
if flavor in ('bash', 'zsh'): | |
return "$'%s'" % s.replace('\\', '\\\\').replace("'", "\\'") | |
elif flavor in ('sh', 'csh'): | |
return "'%s'" % s.replace("'", "'\"'\"'") | |
elif flavor == 'backslash': | |
return backslash_shell_quote_re.sub(r'\\\1', s) | |
else: | |
raise ValueError("Unknown shell quoting flavor %s" % flavor) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment