简体   繁体   English

正确处理bash命令转义字符

[英]Properly dealing with bash commands escape characters

In Linux Bash Scripting在 Linux Bash 脚本中

  • /bin/sh is equivalent to /bin//sh /bin/sh等价于/bin//sh
  • e\\tc converts to etc e\\tc转换为etc
  • \\' converts to ' \\'转换为'
  • "b" converts to b "b"转换为b
  • 'in' converts to in 'in'转换为in

What's a exact way to convert any string into its "bash equivalent"?将任何字符串转换为其“bash 等效项”的确切方法是什么? (In python ideally) (理想情况下在python中)

For example take /"b"'i'n///\\s"h" which converts to /bin/sh as shown below:例如,将/"b"'i'n///\\s"h"转换为/bin/sh ,如下所示:

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

One option is to use the shlex module in the standard library.一种选择是使用标准库中的shlex模块。

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:上面的内容等同于您使用 bash 使用此输入看到的内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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