0

I have a bash file that is looking to find files in a certain directory older than a certain date and delete them. It works fine and I'm able to echo the number of deleted files but I am having problems when I try to get the integer into a variable.

#!/bin/bash

# Make this dynamic to look at different directories.
pathtofolder=/var/www/website/temp2/

if [ $hours ]; then
    # To specify older than one day it is better to talk in hours because 
    # the days integer is just an integer so everything less than 2 days 
    # would be 1 day, so 1 day 23 hours and 59 minutes is not greater than
    # 1 day.
    # For this reason I am using mmin and using the hours in minutes.
    timeinmins=$(($hours*60))
elif [ $mins ]
then
    timeinmins=$mins
else
    # The default is 24 hours but we want to test with 24 minutes
    timeinmins=24
fi

find "$pathtofolder"* -mmin +$timeinmins -exec rm -vr {} \; | output="$(wc -l)"
echo "Files deleted: $output"
echo "Minutes: $timeinmins"

In the above case, the $output is blank.

But this works, below, to just to echo...

find "$pathtofolder"* -mmin +$timeinmins -exec rm -vr {} \; | "Files deleted: $(wc -l)"

Any ideas? thanks in advance.

sdexp
  • 756
  • 4
  • 18
  • 36
  • 2
    `output=$(find ... | wc -l)` – Mat Jun 06 '18 at 15:22
  • 1
    As an aside, `[ $hours ]` is innately buggy -- string-splits and glob-expands the variable's contents and treats the results of that as a test. Consider `[ "$hours" ]` instead, or `[ -n "$hours" ]`, or `[[ $hours ]]`. – Charles Duffy Jun 06 '18 at 15:24
  • I couldn't find any other answers on this topic, so apologies. Mat's answer is very simple and re-usable, so I'm glad I posted for that reason. Thanks also for the advice about `$hours`, Charles, I'd been thinking about setting data types earlier and the `-n` flag is exactly what I needed. – sdexp Jun 06 '18 at 17:09

0 Answers0