Warm tip: This article is reproduced from serverfault.com, please click

Why do these two rm commands produce different outputs?

发布于 2020-11-28 04:48:45

In the first command, the root directory, i.e. te, is not deleted. In the second command, I am trying to add an exception not to delete files of type .log which ends up destroying the source directory. Why do these commands differ and what is the correct way to add an exception without deleting the original directory?

user:~/mnt/test$ rm -rf te/*
user:~/mnt/test$ ls
no.tar  te
user:~/mnt/test$ rm -rf te/* !(*.log)
user:~/mnt/test$ ls
no.tar
Questioner
knowads
Viewed
0
oguz ismail 2020-11-28 17:22:11

The extglob pattern !(*.log) matches the directory te too as its name doesn't end with .log. To delete every file residing in te except those with the extension log, you should do:

shopt -s dotglob    # match hidden files too
echo rm -rf te/!(*.log)

Drop echo if you're happy with the output.