I need to find files in a given directory that have been modified in the last N days, where N is the second argument of the script. Basically, I need to give the command with 2 numbers (arguments) and run a script which would do this.

Is this line of code right in order to find the files?

find . -type f -mtime $2 -exec ls -l {} \;

Sort of. You don't need -exec ls -l {} \;, the find command already lists the files. If you want to list them with more details, you can use find -ls. There's nothing wrong with -exec ls ... either, it's fine if you prefer that, just not needed.

The -mtime N will find files that were modified exactly N days ago. The details are in man find:

  +n     for greater than n,

  -n     for less than n,

   n      for exactly n.

So, to find the files modified in the last 2 days, you would run

find /target/path -mtime -2 -ls

Note that find . will search in the current directory. To search in a specific directory, use a path like find /path/to/dir. If the 1st argument is the target directory, use (remember to always quote your variables):

find "$1" -mtime -"$2" -ls

Also, note that -mtime only deals with 24 hour periods, "days". You'll need to take that into account when writing your command. As explained in man find (this is for -atime but the same applies to -mtime):

File was last accessed n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.