Reputation: 71
I'm trying to pass parameter to rm in bash script to clean my system automatically. For example, I want to remove everything except the *.doc files. So I wrote the following codes.
#!/bin/bash
remove_Target="!*.txt"
rm $remove_Target
However, the output always say
rm: cannot remove ‘!*.txt’: No such file or directory
It is obviously that bash script add single quotes for me when passing the variable to rm. How can I remove the single quotes?
Upvotes: 2
Views: 826
Reputation: 113814
Suppose that we have a directory with three files
$ ls
a.py b.py c.doc
To delete all except *.doc
:
$ shopt -s extglob
$ rm !(*.doc)
$ ls
c.doc
!(*.doc)
is an extended shell glob, or extglob
, that matches all files except those ending in .doc
.
The extglob feature requires a modern bash
.
Alternatively:
find . -maxdepth 1 -type f ! -name '*.doc' -delete
Upvotes: 3