27

When I do

rm file.txt

or

rm *.txt

I'm prompted for each file, since I didn't specify the -f option to rm.

But when I do this:

find . -type f -name '*.txt' | xargs rm

the files are removed without the confirmation.

What is the logics behind this? Is it possible to find the reason in some documentation? I cannot explain why this would be the case.

Martin G
  • 17,357
  • 9
  • 82
  • 98

3 Answers3

30

You have an alias set for the rm command to 'rm -i'. Therefore if you invoke the command directly as in

rm file.txt

or

rm *.txt

the alias will be expanded. If you will call it with xargs as in

find . -type f -name '*.txt' | xargs rm

The rm is passed as a simple string argument to xargs and is later invoked by xargs without alias substitution of the shell. You alias is probably defined in ~/.bashrc, in case you want to remove it.

Harald Gliebe
  • 7,236
  • 3
  • 33
  • 38
  • 1
    This relies on spaces in file names... careful. Use print0 instead. https://stackoverflow.com/a/42119953/370238 – Ray Foss Oct 15 '21 at 21:40
  • 2
    DON"T USE COMMANDS FROM THIS ANSWER. This commands are unsafe for space containing filenames. Use `find -exec` – Mihail H. Jun 04 '22 at 21:37
  • For example, if you have two files (`config file.txt` and `config`) then `find . -type f -name '*.txt' | xargs rm` will delete `config` file but not `config file.txt` file. – Mihail H. Jun 04 '22 at 21:46
18

you can use this simple command to solve your problem

find . -type f -name '*.txt' -delete
Nahum
  • 6,959
  • 12
  • 48
  • 69
Stephen
  • 635
  • 5
  • 7
  • 2
    Nice, but there's a typo, it should be `-type`, not `--type`, otherwise this solution worked well for me – Levon Dec 29 '21 at 17:07
2

Depending on your version of xargs you may have the --no-run-if-empty GNU extension option available to you:

find . -type f -name '*.txt' | xargs  --no-run-if-empty  rm -rf
Angelos
  • 29
  • 3
  • 2
    I know the question is about Linux, but if you are a Mac user like me, this option is implicit and is not needed. – Rafs Dec 16 '22 at 12:58