Symeof
Symeof

Reputation: 113

Properly dealing with bash commands escape characters

In Linux Bash Scripting

What's a exact way to convert any string into its "bash equivalent"? (In python ideally)

For example take /"b"'i'n///\s"h" which converts to /bin/sh as shown below:

r3t@r3t:~/$ /"b"'i'n///\s"h"
$

Upvotes: 1

Views: 168

Answers (1)

jkr
jkr

Reputation: 19260

One option is to use the shlex module in the standard library.

import shlex

text = """\
/"b"'i'n///\s"h"
"""

s = shlex.shlex(text, posix=True)
list(s)
# ['/', 'bin', '/', '/', '/', 'sh']

s = shlex.shlex(text, posix=True)
"".join(s)
# '/bin///sh'

The above is equivalent to what you would see with bash with this input:

$ echo /"b"'i'n///\s"h"
/bin///sh

Upvotes: 1

Related Questions