简体   繁体   中英

Properly dealing with bash commands escape characters

In Linux Bash Scripting

  • /bin/sh is equivalent to /bin//sh
  • e\\tc converts to etc
  • \\' converts to '
  • "b" converts to b
  • 'in' converts to in

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM