It's a trap!



I'll avoid going into a whole load of star wars metaphors here, what i wanted to mention is that sometimes the simplest things can make you fall into a trap that could be disastrous...

In our case all we wanted to do (luckily) was just list the details of all the files modified in a directory in the last week.

Now getting the files in simple enough

find /znextract/logs  -mtime -1
~~~~~~~ lots of file name removed here
/znextract/logs/znextract.log.XCOTRD.BXY783
/znextract/logs/znextract.log.XCOTRD.BXY784
/znextract/logs/znextract.log.XCOTRDHDR.BXY783
/znextract/logs/znextract.log.XCOTRDHDR.BXY784


This returns about 80 lines (notice i say lines and not files here....)

If we want to get the full details of the files we just string some extra options on to the find command


 find /znextract/logs  -mtime -1  -exec ls -l {} \;
~~~~~~~~loads of output removed here
-rw-r--r--   1 zainet   staff           346 Sep 24 13:39 /znextract/logs/znextract.log.XCOTRD.BXY783
-rw-r--r--   1 zainet   staff           346 Sep 24 13:42 /znextract/logs/znextract.log.XCOTRD.BXY784
-rw-r--r--   1 zainet   staff           349 Sep 24 13:39 /znextract/logs/znextract.log.XCOTRDHDR.BXY783
-rw-r--r--   1 zainet   staff           349 Sep 24 13:42 /znextract/logs/znextract.log.XCOTRDHDR.BXY784






Now the thing that confused me here (wheen the script had worked perfectly well on another server) was that appening the -exec switches reutrned thousands of files like it had ignored the initial -mtime flag....

So what's going on?

Well after some confusion and a brief flirtation that it may be a bug one of my colleagues spotted the 'trap' here.

On the original server all of the directories were has 'old' modification times on then so they would never show up in the find command i was using. On this server however the directory modification time was also n the last 7 days so the directory was being returned in the list also...

An ls -l of a directory therefore shows all the files......

To fix this we just add the -type switch to only display files

 find /znextract/logs  -mtime -1 -type f -exec ls -l {} \;
~~so the correct number of lines/files are now shown as the output
-rw-r--r--   1 zainet   staff           346 Sep 24 13:39 /znextract/logs/znextract.log.XCOTRD.BXY783
-rw-r--r--   1 zainet   staff           346 Sep 24 13:42 /znextract/logs/znextract.log.XCOTRD.BXY784
-rw-r--r--   1 zainet   staff           349 Sep 24 13:39 /znextract/logs/znextract.log.XCOTRDHDR.BXY783
-rw-r--r--   1 zainet   staff           349 Sep 24 13:42 /znextract/logs/znextract.log.XCOTRDHDR.BXY784



It's just a good job we didn't -exec rm -rf .........


Comments