rm wildcard not working

I want to delete all .swp files recursively. However:

rm -r *.swp

Gives:

rm: cannot remove ‘*.swp’: No such file or directory

Just to be sure, ls -all gives:

total 628
drwxr--r--.  8 przecze przecze   4096 Aug  3 18:16 .
drwxr--r--. 31 przecze przecze   4096 Aug  3 18:14 ..
-rwxrwxr-x.  1 przecze przecze    108 Jul 28 21:41 build.sh
-rwxrwxr-x.  1 przecze przecze 298617 Aug  3 00:52 exec
drwxr--r--.  8 przecze przecze   4096 Aug  3 18:08 .git
drwxrwxr-x.  2 przecze przecze   4096 Aug  3 18:14 inc
-rw-rw-r--.  1 przecze przecze    619 Aug  3 00:52 main.cc
-rw-r--r--.  1 przecze przecze  12288 Aug  3 17:29 .main.cc.swp
-rw-rw-r--.  1 przecze przecze    850 Aug  1 00:30 makefile
-rw-------.  1 przecze przecze 221028 Aug  3 01:47 nohup.out
drwxrwxr-x.  2 przecze przecze   4096 Aug  3 00:52 obj
drwxrwxr-x.  2 przecze przecze   4096 Aug  3 00:52 out
drwxrwxr-x. 12 przecze przecze   4096 Aug  3 18:14 runs
-rwxr--r--.  1 przecze przecze  23150 Aug  2 18:56 Session.vim
drwxrwxr-x.  2 przecze przecze   4096 Aug  3 18:14 src
-rw-rw-r--.  1 przecze przecze  13868 Jul 31 19:28 tags
-rw-rw-r--.  1 przecze przecze   2134 Aug  3 00:31 view.py
-rw-r--r--.  1 przecze przecze  12288 Aug  3 17:29 .view.py.swp

So there are *.swp files to delete! And rm .build.sh.swp successfully deleted one of them. What am I doing wrong?

Try to match the dot:

$ rm -r .*.swp

I hope this solve your problem.

Answered By: John Goofy

It’s Bash feature controlled by dotglob shell option described in man page:

If set, bash includes filenames beginning with a `.’ in the results
of pathname expansion.

As it’s a Bash feature it causes other commands such as grep, ls
etc. do not handle files starting with . if dotglob is not set as
well. You can check if dotglob is set on your system using shopt
built-in, it must be off if you experience such issues:

$ shopt | grep dotglob
dotglob         off

If shopt was set * would match all files, even these starting
with .. See this example:

$ touch a b c .d
$ ls *
a  b  c
$ ls *d
ls: cannot access '*d': No such file or directory
$ shopt -s dotglob
$ shopt | grep dotglob
dotglob         on
$ ls *
.d  a  b  c
$ ls *d
.d

When dotglob is off you can still create a pattern to handle files
in the current dir together with hidden files:

ls .[!.]* *

or

ls .[^.]* *
Answered By: Arkadiusz Drabczyk
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.