we use the rm
command to delete files from the server/local machine, this is rm
is lifesaver command but sometimes it can be a life destroyer, so here we're gonna master of the rm
command to be a lifesaver, not a destroyer. let's get into that.
Basic
Let's first create fake fille to practice with it:
$ touch myfile-{1..10}.txt
the above command will create 10 files, {1..10}
will just give you 10 number, if you're curious to see run this $ echo {1..100}
.
now to delete single fire,
$ rm myfile-1.txt
this will delete myfile-1.txt
only. to delete multiple files add the file name after it:
$ rm myfile-2.txt myfile-3.txt myfile-4.txt
simpler is that!
if you wish to delete all files
$ rm -rf *
-
-r
flag recursively -
-f
flag force, don't prompt
The above command will delete all the files in the current directory without showing any warning just because we're using -f
flag to force and don't show any warning. using -rf
flag, verify you're in the right directory by using $ pwd
command, then proceed to delete files.
Advance
so far we've learned the basic of deleting files, what about the delete all files except some files, if you want to delete files but not all some fo them you want to keep, let's do it:
first enable the extglob shell option:
# shopt -s extglob
- To delete all files in a directory except filename, run this below command:
$ rm -v !("filename")
- To delete all files with the exception of filename1 and filename2:
$ rm -v !("filename1"|"filename2")
- The example below shows how to remove all files other than all .zip files interactively:
$ rm -i !(*.zip)
- Next, you can delete all files in a directory apart from all .zip and .odt files as follows, while displaying what is being done:
$ rm -v !(*.zip|*.odt)
Once you've done, turn off the extglob shell:
$ shopt -u extglob
There you've it! Thanks for reading my post, let us know what you tink, or find good solution!
my github: https://github.com/lifeeric
Top comments (7)
I just commented this on another post, I thought it might fit here too.
As you perfectly said:
If you want to prevent deleting any important directory via
rm -rf <directory/>*
, there is a neat trick.Create a file named -i in all directories you want to protect. This can be done using
touch -- -i
or
touch ./-i
The * in
rm -r *
will expand the -i File to the command line, so your command ultimately becomesrm -rf -i
Thus rm will prompt you before deleting anything. You can put this file in your /, /home/, /etc/, and so on.
Example:
I use
rm -rf directory
often, but never userm -rf "$directory"
Thanks, Habereder! you're the best this is something awesome I'll definitely do this in future like server host and local ... and will save our life. I love this hack!
Surprised you didn't mention why the name is
rm
Ops, I really sorry! rm stands for "remove". Thank you so much for making me sure!
This is new to me:
Thanx
glad to hear. fist make sure to on
extglob
mode!