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
?
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.
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.
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.
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.
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.
You might consider using os.remove()
instead since it's a great deal less dangerous than what you're attempting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With