Brittany
Brittany

Reputation: 119

Returning list of files based on creation date

I'm just starting out with bourne shell scripting and trying to write a script that will take in two command line arguments: a directory and a file. I want to compare the creation date of the file with those in the directory and print all older files, and then print a count of all newer files.

This is the code I've attempted so far, but I know it's not recognising the directory properly.

#!/bin/sh

directory=$1
file=$2
x=0

for f in $directory
do 
  if [ $f -ot $file ]
  then
    echo "$f"
    x='expr $x+1'
  fi
done

echo "There are $x newer files"

Any tips would be thoroughly appreciated! Thanks

Upvotes: 0

Views: 453

Answers (1)

Amit
Amit

Reputation: 1006

find command provides options to search for files based on timestamps. What you want to achieve can be done without the use of a loop:

# Search for files with modification time newer than that of $file
find $directory -newermm $file

# Search for files with modification time older than that of $file
find $directory ! -newermm $file

Please refer https://www.gnu.org/software/findutils/manual/html_node/find_html/Comparing-Timestamps.html for more details.

However, if you are learning shell scripting and want to write your own script, here are a few suggestions:

  1. For iterating over files in a directory, you can use:

    for f in "$directory"/*
    
  2. As far as I know, -ot compares modification times (and not creation times). For that matter, I doubt if Linux provides creation time of files.

  3. Incrementing x (count of newer files) should be done in an else clause. I would prefer x=$((x+1)), which is supported in all POSIX-compliant shells.

  4. Caveat: Iterating using "$directory/* will not recurse into sub-directories. find will recurse into sub-directories unless you specify the -maxdepth option.

Upvotes: 1

Related Questions