Brittany Brittany - 2 months ago 9x
Bash Question

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.



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

echo "There are $x newer files"

Any tips would be thoroughly appreciated!


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 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 $(ls $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)) but I think it is bash specific.

  4. Caveat: Iterating using $(ls $directory) will not recurse into sub-directories. find will recurse into sub-directories unless you specify the -maxdepth option.