0

I am working on checking if a particular file existing in the directory is older than 30 mins or not.

curr_epch=`date +%s`
curr_epch_buff=`expr $curr_epch - 1800`


ls -l --time-style=+"%s" | grep .part |  awk '{ if (($6 >= $curr_epch_buff)) print $6 }'

However the above code is giving me results irrespective of the condition mentioned.

To debug it, when i tried to take a difference between these 2 values also I am not getting expected results, instead the value in $6 is getting printed as it is:

ls -l --time-style=+"%s" | grep .part |  awk '{ print (expr $6 - $curr_epch_buff) }'

However if i try to subtract a static number using above query, its giving me expected results:

ls -l --time-style=+"%s" | grep .part |  awk '{ print (expr $6 - 200) }'

Can someone please tell me whats wrong with first and second set of codes mentioned above?

  • This is a variant of Use a shell variable in awk - however you shouldn't be relying on parsing the output of ls to find files by age (use something like find -mmin instead) – steeldriver Mar 27 '20 at 16:26
  • mmin will give if file was changed in last specified mins. In my case files will be there which came just now or 10 mins before or 20 or 40. I just need to pull out files which are older than 30 mins before and not anything lesser than that. @steeldriver – Mohammed Haleem S Mar 27 '20 at 16:48

2 Answers2

1

Use $(...) instead of `...` -- see https://mywiki.wooledge.org/BashFAQ/082
bash can do arithmetic, you don't need to call out to expr.
Don't parse ls

curr_epch_buff=$( date -d '30 minutes ago' +%s )

for file in *.part; do
    file_mtime=$( stat -c '%Y' "$file" )
    if (( file_mtime < curr_epch_buff )); then
        echo "$file is older than 30 minutes"
    fi
done

The problems with awk '{ print (expr $6 - $curr_epch_buff) }':

  • curr_epch_buff is treated as an awk variable. It is unset.
  • in awk $n acts like an operator, to return the contents of the field number referenced by n
  • in a numeric context, an unset variable is treated as the number 0
  • so $curr_epch_buff is the same as $0 i.e. the entire record.
  • expr is also an unset variable
  • expr $6 is string contatenation, the result is the contents of $6
  • $6 - $0
    • the record does not start with a number, it starts with the file's permission string as returned by ls -l
    • awk treats a string that does not start with numbers as zero

The final result is the value of $6

glenn jackman
  • 85,964
0
if [ -z "$(find . -name '*.part' -mmin -30)" ]
then
   echo ".part file is old"
else
   echo ".part file is recent"
fir
  • does that work? my man page for find says that "find exits with status 0 if all files are processed successfully, greater than 0 if errors occur.", it doesn't say anything about the exit status being affected by files being found, or not found (unlike grep). – ilkkachu Mar 27 '20 at 16:59
  • @ilkkachu you are quite right. I'll try to correct my ways. – Gerard H. Pille Mar 27 '20 at 17:21