Linux Commands – find
Hello Everyone
Welcome to CloudAffaire and this is Debjeet.
In the last blog post, we have discussed curl command in Linux which is used to interact with servers.
https://cloudaffaire.com/linux-commands-curl/
In this blog post, we will discuss find command in Linux. find command is used to search for files in a directory hierarchy. find command may begin with the options, followed by a list of files or directories that should be searched and finally a list of expressions describing the files we wish to search for.
Linux Commands – find:
Find command is mainly used to search files and directories based on different conditions and perform an action based on the outcome of the search result. Find command supports a plethora of options which is mainly divided in three categories
- Behavioral options: Controls how find command behave, like how many levels inside a directory and subdirectory you want to traverse, etc.
- Test options: Controls the search conditions, like what type of file or what file name you want to search.
- Action options: Controls the action that you want to perform on the search result, like listing the file details, etc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
########################### ## Linux Commands | find ## ########################### ## Prerequisites: One Unix/Linux/POSIX-compliant operating system with bash shell ##----- ## find ##----- ## find [option] [file...] [expression] sudo find /etc -name "*.conf" ## list all files with .conf extension in /etc sudo find /dev -type b ## list all block device in /dev sudo find /etc -empty -type f ## list all empty files in /etc sudo find /home -executable -type f ## list all user execuatable files sudo find /home -newerat '2020-07-01' ## list all files accessed post 2020-07-01 sudo find /var -size +10M -type f -exec du -h {} + ## list all files having size > 10 MB in /var dir |
Find test conditions:
You can use find -amin n to find files whose atime (access time) changed in n minutes ago. You can use find -mmin n option to find files whose mtime (modify time) changed in n minutes ago. You can use find -cmin n option to find files whose ctime (changed time) changed in n minutes ago.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
## ----------------- ## find test options ## ----------------- ## create one dir and file mkdir mydir && cd mydir ## create one directory and get inside the directory touch myfile ## create a file named myfile stat myfile ## get myfile atime, mtime and ctime ## Access: 2020-07-06 03:38:32.058952582 +0000 ## Modify: 2020-07-06 03:38:32.058952582 +0000 ## Change: 2020-07-06 03:38:32.058952582 +0000 ## find -amin n or -mmin n or -cmin n options find -amin 1 ## returns myfile find -amin 10 ## returns empty find -mmin 1 ## returns myfile find -amin 10 ## returns empty find -cmin 1 ## returns myfile find -amin 10 ## returns empty |
You can use find -atime n option to find files that was last accessed n*24 hours ago. You can use find -mtime n to find files that was last modified n*24 hours ago. You can use find -ctime n to find files whose status was last changed n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed or modified or changed, any fractional part is ignored, so to match -atime +1 or mtime +1 or ctime +1, a file has to have been accessed or modified or changed at least two days ago.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
## find -atime n or -mtime n or -ctime n options mytime=$(date --date='1 days ago') touch -d "$mytime" myfile ## change myfile atime and mtime 24 hours back stat myfile ## get file atime, ctime and mtime ## Access: 2020-07-05 03:47:48.000000000 +0000 ## Modify: 2020-07-05 03:47:48.000000000 +0000 ## Change: 2020-07-06 03:52:06.325846163 +0000 find -atime 1 ## returns myfile find -mtime 1 ## returns myfile find -ctime 1 ## returns empty, as ctime was not changed sudo find /var -ctime 2 | wc ## list count of all files in /var dir whose ctime >= 2 days |
You can use find -anewer file option to find files that was last accessed more recently than file was modified. You can use find -cnewer file option to find files whose status was last changed more recently than file was modified.
1 2 3 4 5 6 7 8 9 10 11 |
## find -anewer file or -nnewer file options touch -a myfile ## change atime & ctime stat myfile ## get file atime, ctime and mtime ## Access: 2020-07-06 04:08:05.225719878 +0000 ## Modify: 2020-07-05 03:47:48.000000000 +0000 ## Change: 2020-07-06 04:08:05.225719878 +0000 find -anewer myfile ## returns myfile find -cnewer myfile ## returns myfile |
You can use find -newer file option to find files that was modified more recently than file in the option argument. You can also use find -newerXY reference option to provide a custom timestamp as reference to compare file atime, ctime or mtime. The reference argument is normally the name of a file (and one of its timestamps is used for the comparison) but it may also be a string describing an absolute time. X and Y are placeholders for other letters, and these letters select which time belonging to how reference is used for the comparison.
- a: The access time of the file reference
- B: The birth time of the file reference
- c: The inode status change time of reference
- m: The modification time of the file reference
- t: reference is interpreted directly as a time
Note: Some combinations are invalid; for example, it is invalid for X to be t.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
## find -newer file or -newerXY reference options mytime=$(date --date='1000 days ago') touch -d "$mytime" myfile ## change myfile atime and mtime 1000 days ago touch mynewfile ## create a new file named mynew file stat myfile ## get file atime, ctime and mtime of myfile ## Access: 2017-10-10 04:20:13.000000000 +0000 ## Modify: 2017-10-10 04:20:13.000000000 +0000 ## Change: 2020-07-06 04:20:13.686452755 +0000 stat mynewfile ## get file atime, ctime and mtime of mynewfile ## Access: 2020-07-06 04:20:13.686452755 +0000 ## Modify: 2020-07-06 04:20:13.686452755 +0000 ## Change: 2020-07-06 04:20:13.686452755 +0000 find -newer "myfile" ## returns mynewfile find -newermt '2020-01-01' find -newerat '2010-01-01' ## returns myfile & mynewfile rm mynewfile |
You can use find -used n option to find file that was last accessed n days after its status was last changed.
1 2 3 |
## find -used n option sudo find /var -used 2 |
You can use find -executable option to find files that are executable and directories that are searchable. You can use find -writable option to find files that are writable. You can use find -readable option to find files which are readable.
1 2 3 4 5 6 7 8 9 10 |
## find -executable or -writable or -readable option chmod 777 myfile ## make myfile readable, writable and execuatble ls -l myfile ## -rwxrwxrwx 1 debjeet debjeet 0 Oct 10 2017 myfile find -executable ## returns myfile find -writable ## returns myfile find -readable ## returns myfile |
You can use find -perm mode option to find files with a specific set of permission bit. mode supports both symbolic representation and numeric representation of the permission bit.
1 2 3 4 |
## find -perm mode option find -perm 777 ## returns myfile find -perm u=wrx,g=wrx,o=wrx ## returns myfile |
You can use find -empty option to find files and directories that are empty.
1 2 3 4 5 |
## find -empty option find -empty ## returns myfile sudo find /var -empty -type d ## returns all empty directory in /var sudo find /var -empty -type f ## returns all empty files in /var |
You can use find -size n[cwbkMG] option to find files with n units of space. The following suffixes can be used:
- b: for 512-byte blocks (this is the default if no suffix is used)
- c: for bytes
- w: for two-byte words
- k: for Kilobytes (units of 1024 bytes)
- M: for Megabytes (units of 1048576 bytes)
- G: for Gigabytes (units of 1073741824 bytes)
Note: The size does not count indirect blocks, but it does count blocks in sparse files that are not actually allocated.
1 2 3 |
## find -size n[cwbkMG] option sudo find /var -size +10M ## returns all files with size > 10 MB in /var |
You can use find -gid n option to find files whose group owners group id is n. You can use find -group gname option to find files whose group owners group name is gname (gid also allowed with -group option). You can use find -uid option to find files whose owner user id is n. You can use find -user uname option to find files whose owner user name is uname (uid also allowed with -user option).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
## find -gid n or -group gname or -uid n or -user uname options sudo groupadd -g 1111 mygroup ## create a user and add to group sudo useradd -M -u 1111 -g mygroup myuser sudo chown myuser:mygroup myfile ## chnage myfile owner and group find -gid 1111 ## returns myfile find -group mygroup ## returns myfile find -uid 1111 ## returns myfile find -user myuser ## returns myfile sudo rm -rf myfile && touch myfile |
You can use find -nogroup option to find files which has no group corresponding to its numeric group id. You can use find -nouser option to find files which has no user corresponding to its numeric user id.
1 2 3 4 5 |
## find -nogroup or -nouser options sudo find /var -nogroup | wc ## returns all files which don't have any owner group in /var sudo find /var -nouser | wc ## returns all files which don't have any owner user in /var |
You can use find -name pattern option to find files based on file name given in the pattern (pattern supports regular expression). You can also use find -iname pattern option to find files based on file name given in the pattern but in this case the pattern with be case insensitive.
1 2 3 4 5 6 7 |
## find -name pattern or -iname pattern options find -name "my*" ## returns myfile find -iname MYFILE find -iname myFILE find -iname "Myf*" |
You can use find -lname pattern option to find a symbolic link whose contents match shell pattern pattern. You can also use -ilname pattern option to find a symbolic link whose contents match shell pattern pattern but the pattern will be case insensitive in this case.
1 2 3 4 5 6 7 8 9 |
## find -lname pattern or -ilname pattern options ln -s myfile myslink ## create a symbolic link named mylink pointing to myfile find -lname "my*" ## returns myslink find -ilname MYFILE find -ilname myFILE find -ilname "My*" |
You can use find -inum n option to find files having inode number n.
1 2 3 4 5 |
## find -inum n option ls -i myfile ## returns 875411 myfile find -inum 875411 ## returns myfile |
You can use find -type n option to find files and directories based on file type. Below file type arguments are supported:
- b: block (buffered) special
- c: character (unbuffered) special
- d: directory
- p: named pipe (FIFO)
- f: regular file
- l: symbolic link
- s: socket
- D: door (Solaris)
1 2 3 4 5 |
## find -type option find -type l ## returns myslink find -type f ## returns myfile |
You can use find -fstype type option to find files having filesystem of type type.
1 2 3 4 5 |
## find -fstype type option find myfile -printf '%F\n' ## returns xfs in my system find -fstype xfs ## returns myfile |
You can use find -path pattern option to find file having path matching to the path given in the pattern. find -ipath pattern performs the same action, only the search is case insensitive.
1 2 3 4 5 6 7 8 9 |
## find -path pattern or -ipath pattern options pwd ## returns /home/debjeet/mydir find /home -path "*mydir/myfile" ## returns /home/debjeet/mydir/myfile find /home -ipath "*mydir/myfile" find /home -ipath "*MYDIR/Myfile" find /home -ipath "*MYDIR/*FILe" |
You can use find -regex pattern option to find file name matching regular expression pattern. find -regex pattern option does the same thing, only the search will be case insensitive.
1 2 3 4 5 6 7 |
## find -regex pattern or -iregex pattern options find -regex ".*/myfile" ## returns myfile find -iregex ".*/myfile" find -iregex ".*/MYFILE" find -iregex ".*/Myfile" |
You can use find -links n option to find files having n links.
1 2 3 4 5 6 7 8 9 10 |
## find -links n option ln myfile myhlink ## create a hard link named myhlink to myfile ls -l find -links 1 ## returns myslink find -links 2 ## returns myfile & myhlink rm -rf myhlink |
Find actions:
You can use find -delete option to delete files if matches the search criteria.
1 2 3 4 5 6 7 8 9 |
## find -delete option touch mynewfile ## create a file ls -l find -name "mynewfile" -delete ## delets mynewfile ls -l |
You can use find -exec command option to execute the command if find matches the search criteria. The -exec option has two variants, {} \; and {} +. You can use find -ok command option which is similar to -exec but ask the user first before executing each instance of the command.
1 2 3 4 5 6 7 |
## find -exec command or -ok command options find -name "myfile*" -exec ls -l {} + ## list myfile find -name "myfile*" -exec ls -l {} \; find -name "myfile*" -ok ls -l {} + find -name "myfile*" -ok ls -l {} \; |
You can use find -execdir command option which is pretty similar to -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. This a much more secure method for invoking commands, as it avoids race conditions during the resolution of the paths to the matched files. find -okdir command option is similar to -execdir option but ask the user first before executing each instance of the command.
1 2 3 4 5 6 7 8 9 10 11 12 |
## find -execdir command or -okdir command options mkdir -p mydir1/mydir2/mydir3 ## create some dirs and file touch mydir1/mydir2/mydir3/debjeet find -name "debjeet" -execdir ls -l {} + find -name "debjeet" -execdir ls -l {} \; find -name "debjeet" -okdir ls -l {} + find -name "debjeet" -okdir ls -l {} \; rm -rf mydir1 |
You can use find -ls option to list current file in ls -dils format on standard output.
1 2 3 |
## find -ls option find -name "myfile*" -ls |
You can use find -fprint file option to print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated.
1 2 3 4 |
## find -fprint file option find -name "myfile*" -fprint myoutput cat myoutput && rm myoutput |
You can use find -print option to print the full file name on the standard output, followed by a newline.
1 2 3 |
## find -print option find -name "myfile*" -print |
You can use find -printf option to print details of the file and directories that are being searched. printf provides lots of options to print all most all attributes of a file or directory in Unix. For more details please refer find manual.
1 2 3 |
## find -printf format option find -name "myfile*" -printf "file_name=%p file_type=%y inode=%i\n" |
Find options:
You can use find -maxdepth levels option to restrict the search to descend at most levels (a non-negative integer) levels of directories below the command line arguments. -maxdepth 0 means only apply the tests and actions to the command line arguments. You can use find -mindepth levels option to not apply any tests or actions at levels less than levels (a non-negative integer). -mindepth 1 means process all files except the command line arguments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
## ------------ ## find options ## ------------ ## find -maxdepth levels or -mindepth levels options mkdir -p mydir1/mydir2/mydir3 ## create some directories and files touch mydir1/myfile1 touch mydir1/mydir2/myfile2 touch mydir1/mydir2/mydir3/myfile3 find -name "myfile*" | wc find -maxdepth 1 -name "myfile*" | wc find -maxdepth 2 -name "myfile*" | wc find -maxdepth 3 -name "myfile*" | wc find -name "myfile*" | wc find -mindepth 1 -name "myfile*" | wc find -mindepth 2 -name "myfile*" | wc find -mindepth 3 -name "myfile*" | wc rm -rf mydir* |
You can use find -D debugoptions option to print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Valid debug options include
- help: Explain the debugging options
- tree: Show the expression tree in its original and optimized form.
- stat: Print messages as files are examined with the stat and lstat system calls.
- opt: Prints diagnostic information relating to the optimization of the expression tree.
- rates: Prints a summary indicating how often each predicate succeeded or failed.
1 2 3 4 5 6 7 |
## find -D debugoptions option find -D help sudo find -D tree /var -name "*.conf" sudo find -D stat /var -name "*.conf" sudo find -D opt /var -name "*.conf" sudo find -D rates /var -name "*.conf" |
You can use find -Olevel option to enable query optimization. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimizations performed at each optimization level are as follows:
- 0: Equivalent to optimization level 1.
- 1: This is the default optimization level and corresponds to the traditional behavior. Expressions are reordered so that tests based only on the names of files.
- 2: Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode.
- 3: At this optimization level, the full cost-based query optimizer is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary.
1 2 3 4 5 6 7 |
## find -Olevel option sudo find -D opt,rates -O1 / -name "*.xml" -type f sudo find -D opt,rates -O2 / -name "*.xml" -type f sudo find -D opt,rates -O3 / -name "*.xml" -type f |
You can use find -H or -L or -P options to control the treatment of symbolic links.
- -P: Never follow symbolic links. This is the default behavior.
- -L: Always follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself.
- -H: Sometimes follow symbolic links. Follows symbolic link when a file specified on the command line is a symbolic link, and the link can be resolved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
## find -H or -L or -P options mkdir mydir{1,2,3} ## create some files, dir, and links touch mydir1/myfile1 mydir2/myfile2 mydir3/myfile3 ln -s mydir2 mylink2 cd mydir1 ln -s ../mydir3 mylink3 cd .. tree ## . ## ├── mydir1 ## │ ├── myfile1 ## │ └── mylink3 -> ../mydir3 ## ├── mydir2 ## │ └── myfile2 ## ├── mydir3 ## │ └── myfile3 ## ├── myfile ## ├── mylink2 -> mydir2 ## └── myslink -> myfile find -P mydir1 mylink2 -printf 'find_name=%p file_type=%y inode=%i\n' find -H mydir1 mylink2 -printf 'find_name=%p file_type=%y inode=%i\n' find -L mydir1 mylink2 -printf 'find_name=%p file_type=%y inode=%i\n' ## ------- ## cleanup ## ------- cd rm -rf mydir sudo userdel -rf myuser sudo groupdel mygroup |
Hope you have enjoyed this article. In the next blog post, we will discuss grep command in Linux.