I am trying to run:
for i in *; do sudo rm $i; done
The problem is that there is something wrong with glob expansion and I get the error:
rm: cannot remove '*': No such file or directory
I get this error for each time that the loop runs. The files are deleted (even though I used CTRL+C to stop the errors) but I am getting this error that I should not get as I did not escape the glob symbol and I did not use any single quotation marks.
This has always worked in the past without the error.
Also, if I run:
sudo rm 1*
for example, it will run use the glob properly. However, if I run:
for i in 1 2 3 4 5 6 7 8 9; do sudo rm $i*; done
I get the following:
rm: cannot remove '1*': No such file or directory
rm: cannot remove '2*': No such file or directory
rm: cannot remove '3*': No such file or directory
rm: cannot remove '4*': No such file or directory
rm: cannot remove '5*': No such file or directory
rm: cannot remove '6*': No such file or directory
rm: cannot remove '7*': No such file or directory
rm: cannot remove '8*': No such file or directory
rm: cannot remove '9*': No such file or directory
What is wrong with my globs in loops now?
I am not interested in different methods of deleting the files. I am only interested in what is wrong with glob expansion. Glob expansion seems to work (all the files are deleted) but then it wants to loop again like I escaped the glob character instead of being done.
EDIT:
It seems this is only a problem when there is an excessively large number of files. I ran the command: for i in *; do sudo rm $i; done
on the same directory with only 800 files and I could not reproduce the error.
I also tested the command: for i in 1 2 3 4 5 6 7 8 9; do sudo rm $i*; done
and I did not get an error when only deleting ~800 files and some numbered dummy files.
"too many files to delete in one
rm
command." - is a problem with a well-known solution - usefind
andxargs
. Together they handle "too many files" as well as "files with funny characters". Readman find
andman xargs
.Your particular case, "
for i in *; do sudo rm $i; done
" would be expressed aswill run as few
sudo rm
commands as it can, stuffing as many filenames as it can on a line (seexargs --show-limits </dev/null
).Or, one could
but tastes vary.
If you need
sudo
to remove anything in this directory, you most certainly don’t have read permissions either, which preventsbash
from performing the glob expansion – run your loop in a root shell instead: