2. More examples with find
-
Let's create some test files:
mkdir -p test/dir-{001..100}
touch test/dir-{001..100}/file-{A..Z}
The command
touch
in this case creates empty files.ls test/
ls test/dir-001/
ls test/dir-002/
-
Find all the files named
file-A
:find test -type f -name 'file-A'
find test -type f -name 'file-A' | wc -l
-
Create a timestamp file:
touch test/timestamp
This creates an empty file and sets its modification time to the current time. We can verify this with
stat
which shows everything that the system knows about a file:stat test/timestamp
touch test/timestamp
stat test/timestamp
We can see that after the second
touch
the times have been updated. -
Next, let's use
find
to update all files namedfile-B
:find test -name 'file-B' -exec touch '{}' ';'
-
Now let's use
find
to identify the updated files by comparing them to the reference filetimestamp
:find test -type f -newer test/timestamp
find test -type f -newer test/timestamp | wc -l
The result contains all 100 instances of
file-B
. Since we did atouch
on them after updatingtimestamp
, they are now "newer" than the filetimestamp
. -
Let's find again the files and directories with bad permissions:
find test \( -type f -not -perm 0600 \) \
-or \( -type d -not -perm 0700 \)find test \( -type f -not -perm 0600 \) \
-or \( -type d -not -perm 0700 \) \
| wc -l -
Let's add some actions to the command above in order to fix the permissions:
find test \
\( \
-type f -not -perm 0600 \
-exec chmod 0600 '{}' ';' \
\) -or \
\( \
-type d -not -perm 0700 \
-exec chmod 0700 '{}' ';' \
\)find test \( -type f -not -perm 0600 \) \
-or \( -type d -not -perm 0700 \)find test \( -type f -perm 0600 \) \
-or \( -type d -perm 0700 \)find test \( -type f -perm 0600 \) \
-or \( -type d -perm 0700 \) \
| wc -lNote: This example is a bit complex just to illustrate the logical operators and parantheses, however we could have done it in two simpler steps, like this:
find test -type f -not -perm 0600 \
-exec chmod 0600 '{}' ';'find test -type d -not -perm 0700 \
-exec chmod 0700 '{}' ';' -
Let's try some more tests:
Find files or directories whose contents or attributes were modified more than 1 minute ago:
find test/ -cmin +1 | wc -l
Less than 10 minutes ago:
find test/ -cmin -10 | wc -l
Find files or directories whose contents were modified more than 1 minute ago:
find test/ -mmin +1 | wc -l
Less than 10 minutes ago:
find test/ -mmin -10 | wc -l
Find files or directories whose contents or attributes were modified more than 7 days ago:
find test/ -ctime +7 | wc -l
Find files or directories whose contents were modified less than 7 days ago:
find test/ -mtime -7 | wc -l
Find empty files and directories:
find test/ -empty | wc -l