如何替换命令中的特殊字符以使其在 shell 中有用

How to replace a special character in a command to make it useful in the shell

import os
string = "mkdir P&C_directory && pwd'
os.system(string)

shell 结果是:

string = "mkdir P&d_directory"
In [11]: os.system(string)
sh: 1: d_directory: not found

如何将字符串中的任何特殊字符替换为“\special_character”

& 字符保留用于特殊用途 (https://www.cyberciti.biz/faq/linuxunix-rules-for-naming-file-and-directory-names/)。最好不要将这些保留字符用于 Linux 和 Unix 文件系统。但是,如果你真的需要使用它,或者你想在 file-system 而不是 Linux file-system (ext2 / ext3 / etx4) 上使用它,当然,你可以做吧。

这可以使用引号来完成:mkdir '/tmp/test&test' 甚至可以使用转义字符:mkdir /tmp/test\&test.

root@vusolose:~# python
Python 2.7.16 (default, May  4 2021, 14:15:48)
[GCC 9.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> cmd1="mkdir '/tmp/test&test' && ls /tmp"
>>> os.system(cmd1)
test&test
0