简体   繁体   中英

Bash shell script FOR loop through files older than specific date

I'm trying to identify and delete files older than a certain constant date in my shell script. Below is a script that just counts it. I can't use find or anything else that will build up arguments because there's 1.5m files in this directory and I get the

-bash: /usr/bin/find: Argument list too long

error. So my current abbreviated scripts is:

y=0;
cond=$(date -d 2020-10-15 +%s)
for FILE in *tele*
do
  if [ $FILE -ot $cond ]
  then
    y=$((y+1))
  fi
done
echo $y

It should count all the files (cond date is in future) but it retuns 0. I think I'm not using the correct date types for comparison.

Here's a simple trick to count files:

find … -printf x | wc -c

Basically, for each file print the byte "x", then count the number of bytes.


As for why your script is failing, the synopsis for -ot is [ PATH1 -ot PATH2 ] , which you could easily emulate like this (untested):

reference="$(mktemp)"
touch "--date=@${cond}" "$reference"
…
if [[ "$path" -ot "$reference" ]]
then
    …

Runtime comparison:

$ cd "$(mktemp --directory)"
$ touch {1..100000}
$ time find . -mindepth 1 -printf x | wc -c
100000

real    0m0.072s
user    0m0.036s
sys     0m0.040s
$ time for FILE in *
do
   if [ $FILE -ot 0 ]
   then
       y=$((y+1))
   fi
done

real    0m0.438s
user    0m0.334s
sys     0m0.105s

The find solution is ~6 times faster for 100000 files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM