3

I'm trying to create a for loop to delete log files older than 15 days. Below is my script:

#!/bin/sh
path="/home/test"

logpath="$path/logs"
for logfile in `find $logpath -mtime +14 -type f -name *.log`
do
    echo "Deleting Log File: " $logfile
    rm -rf $logfile
done

It keeps throwing an error:

find: paths must precede expression
Usage: find [-H] [-L] [-P] [path...] [expression]

Any ideas?

4
  • Have you tried putting $logpath before *.log ? Commented Aug 1, 2016 at 8:22
  • 1
    Try wrapping *.log within double-quotes like "*.log" Commented Aug 1, 2016 at 8:24
  • How do you execute the script? It's working fine for me when executing it like './test.sh' Commented Aug 1, 2016 at 8:31
  • i execute using crontab. Commented Aug 1, 2016 at 8:36

3 Answers 3

4

Please try this - added single quotes

#!/bin/sh
path="/home/test"

logpath="$path/logs"
for logfile in `find $logpath -mtime +14 -type f -name '*.log'`
do
    echo "Deleting Log File: " $logfile
    rm -rf $logfile
done
Sign up to request clarification or add additional context in comments.

Comments

2

You could use the exec param of find to get rid of the for loop:

find $logpath -mtime +14 -type f -name '*.log' -exec rm -rf {} \;

or like @Patryk Obara says :

find $logpath -mtime +14 -type f -name '*.log' -delete

which enable -depth implicitly.

You can test it like this :

mkdir test
cd test
touch test1.log
touch test2.log
find . -type f -name '*.log'
ls
> test1.log  test2.log
find . -type f -name '*.log' -delete
> empty

9 Comments

Or even better, find has shortcut for that, you can use -delete instead of -exec rm -rf {} \;.
This is incorrect and obviously wasn't tested. You have the same issue as OP: you must escape the * in the -name with single quotes. -name '*.log'...
@smassey I added a script that works. Could you explain why you think single quotes would help ?
@Till If you don't quote the argument, the shell expands it immediately to the files that match in the current directory. Maybe it worked for you because you have no *.log files in your current directory.
@Till did you just "fake" the output of your script? smassey@hacklabs:/tmp/test $ find ./ -type f -name *log find: paths must precede expression: test1.log is what you would actually see.
|
0

Logrotate is a better choice for this kind of job, here's a link to it's documentation - http://www.linuxcommand.org/man_pages/logrotate8.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.