find

find is a powerful utility used for locating files and directories on a file system. It includes options that allow you to execute commands on the files that were found and has a number of criteria to help improve your search.

Basic Syntax

The basic syntax of the find command is:

find [path] [expression]

  • path: This specifies the directory to search. If it is not specified, the search will start from the current working directory.
  • expression: This specifies the criteria to be used in the search.

Commonly Used Options

  • -name: Search for files and directories with a specific name.
  • -type: Search for files of a specific type, such as regular files f, directories d, or symbolic links l.
  • -perm: Search for files based on set permissions.
  • -mtime: Search for files that were modified N days ago.
  • -atime: Search for files that were accessed N days ago.
  • -mmin: Search for files that were modified N minutes ago.
  • -amin: Search for files that were accessed N minutes ago.
  • -size: Search for files that are a certain size.
  • -user: Search for files that belong to a specific user.
  • -group: Search for files that belong to a specific group.
  • -exec: This executes a command on the files that match the search criteria.

Useful Examples

  • find /etc -type f -name "passwd": Search for regular files named passwd in the /etc directory.
  • find /home -type f -name *password*: Search for regular files that contain password in the name in the /home directory.
  • find /var -type f -not -name root: Search for regular files not owned by the user root in the /var directory.
  • find /home -user alice -size +10M: Search for any files in the /home directory that belong to the user alice and are larger than 10 megabytes.
  • find /var/log -type f -mtime +7 -exec rm {} \;: Search for regular files in the /var/log directory that were modified more than 7 days ago and delete them.
  • find /usr/bin -type f -name "*.sh" -exec chmod +x {} \;: Search for files in the /usr/bin directory that have a .sh extension and makes them executable.
  • sudo find . -maxdepth 1 -type f -execdir cp {} {}.BAK \; -execdir mv {}.BAK /mnt/backup \;: Restrict search to a depth level of 1 and search for regular files in the current directory, create a copy of each one, append a .BAK file extension and move the copies to the /mnt/backup directory.
  • find /var/log -type f -print0 | xargs -0 grep -nE "warning|error" --color=auto: Search for all files in the /var/log directory that contains strings with the words warning or error, highlights the matched terms and lists the file’s name and the line the match was found on.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

  1. […] Once installed, let’s first allow TCP traffic over your SSH port so that you don’t get locked out of…

  2. […] have the option to choose between Password and SSH key selection. Learn more about SSH keys here. It’s recommended…