Reputation: 137
I want to find the specific file types in a particular directory. Once the file type got matched I need to delete the file. As I have used the below codes but it does not work. Could you suggest solution for this?
directory=/var/log/myFiles
if [ -d $directory ]
then
for file in $directory/*
do
if [ -f $file ]
then
if [$file==*.log.1]
then
rm file
fi
fi
done
fi
Upvotes: 2
Views: 493
Reputation: 12347
Shorter and faster solution is using find
and xargs
:
find /var/log/myFiles -type f -name '*.log.1' | xargs rm
Before doing mass deletes like the above, I do a safety check first, like so:
find /var/log/myFiles -type f -name '*.log1' | xargs ls -1
If your files contain spaces or newlines, use NUL
-delimited form of the command above:
find /var/log/myFiles -type f -name '*.log.1' -print0 | xargs -0 rm
Upvotes: 1
Reputation: 12393
You don't actually need a script, find + exec could do that:
find /var/log/myFiles -name "*.log.1" -exec echo rm {} \;
Your script fails:
$ ./script.sh
./script.sh: line 11: [/var/log/myFiles/a==*.log.1]: No such file or directory
./script.sh: line 11: [/var/log/myFiles/a.log.1==*.log.1]: No such file or directory
because the if
line is completely wrong, it should be something
like:
if [[ "$file" == *.log.1 ]]
Upvotes: 1