Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux shell script for loop error

Tags:

linux

shell

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?

like image 763
Arnold Cristobal Avatar asked Apr 09 '26 08:04

Arnold Cristobal


2 Answers

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
like image 114
Jyothi Avatar answered Apr 10 '26 23:04

Jyothi


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
like image 20
Till Avatar answered Apr 10 '26 21:04

Till



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!