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

Time:03-09

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

shell result is :

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

How to replace any special character in string to "\special_character"

CodePudding user response:

The & character is reserved for special purposes (https://www.cyberciti.biz/faq/linuxunix-rules-for-naming-file-and-directory-names/). It is better not to use these reserved characters for Linux and Unix file systems. However, if you really need to use it, or if you want to use it on a file-system other than the Linux file-system (ext2 / ext3 / etx4), of course, you can do it.

This can be done using quotation marks: mkdir '/tmp/test&test' or even using the escape character: 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
  • Related