Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File deletion using rm command

I want to make sure that I delete required files. I have code something like

dir="/some/path/"
file = "somefile.txt"
cmd_rm= "rm -rf "+dir + file
os.system(cmd_rm)

The dir and file values are fetched from a database. How can I make sure I never end up running rm -rf /?

What things should I check before doing rm -rf?

like image 812
webminal.org Avatar asked Feb 16 '10 08:02

webminal.org


People also ask

Can you delete a file removed by the rm command?

To remove (or delete) a file in Linux from the command line, use either the rm (remove) or unlink command. The unlink command allows you to remove only a single file, while with rm , you can remove multiple files at once.

How remove deleted file in Linux?

On Linux or Unix systems, deleting a file via rm or through a file manager application will unlink the file from the file system's directory structure; however, if the file is still open (in use by a running process) it will still be accessible to this process and will continue to occupy space on disk.

How do I delete multiple files in rm?

Deleting multiple files To delete multiple files at once, simply list all of the file names after the “rm” command. File names should be separated by a space. With the command “rm” followed by multiple file names, you can delete multiple files at once.

Does rm RF delete everything?

rm -rf / — Deletes Everything!The command rm -rf / deletes everything it possibly can, including files on your hard drive and files on connected removable media devices. This command is more understandable if it's broken down: rm — Remove the following files.


2 Answers

Don't use the -r switch if you just want to remove a single file. Also, there could be spaces in the file name.

Better use the functions in Python's os module instead:

dirname = "/some/path/"
filename = "somefile.txt"
pathname = os.path.abspath(os.path.join(dirname, filename))
if pathname.startswith(dirname):
   os.remove(pathname)

Normalizing the path with abspath and comparing it against the target directory avoids file names like "../../../etc/passwd" or similar.

like image 153
sth Avatar answered Oct 12 '22 20:10

sth


You might consider using os.remove() instead since it's a great deal less dangerous than what you're attempting.

like image 38
brettkelly Avatar answered Oct 12 '22 18:10

brettkelly