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
touchin 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/timestampThis creates an empty file and sets its modification time to the current time. We can verify this with
statwhich shows everything that the system knows about a file:stat test/timestamptouch test/timestampstat test/timestampWe can see that after the second
touchthe times have been updated. -
Next, let's use
findto update all files namedfile-B:find test -name 'file-B' -exec touch '{}' ';' -
Now let's use
findto identify the updated files by comparing them to the reference filetimestamp:find test -type f -newer test/timestampfind test -type f -newer test/timestamp | wc -lThe result contains all 100 instances of
file-B. Since we did atouchon 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 -lLess than 10 minutes ago:
find test/ -cmin -10 | wc -lFind files or directories whose contents were modified more than 1 minute ago:
find test/ -mmin +1 | wc -lLess than 10 minutes ago:
find test/ -mmin -10 | wc -lFind files or directories whose contents or attributes were modified more than 7 days ago:
find test/ -ctime +7 | wc -lFind files or directories whose contents were modified less than 7 days ago:
find test/ -mtime -7 | wc -lFind empty files and directories:
find test/ -empty | wc -l