How to Use Find Command in Linux Bash with 15 Example

In this blog post, I’m going to cover how to use “find” command with 15 examples. Find command is one of the most powerful commands in Linux bash. It allows you to find files and directories within your file system. But that’s not all, it can do a lot more, especially when combined with other commands. So without further delay. Let’s get started.

1-finding “file1.txt” within the current directory (-name) option to specify filename

find . -name "file1.txt"

2- find any text file using wildcard “*” and -iname to ignore case sensitivity

find . -type f -iname "*.txt"

3- find any bash/shell script in dir1 and dir2 (-type f) to find only files

find dir1 dir2 -type f -iname "*.sh"

4- Find files of type jpg or mp3. (-o) option is a logical OR, which means jpg or mp3

find . -type f -iname "*.jpg" -o -iname "*.mp3"

5- Find files created within last 24 hours (-mtime -1)

find . -type f -mtime -1

6- Find files older than 1 day

find . -type f -mtime +1

7- Find files older than one day and newer than 10

find . -type f -mtime +1 -a -mtime -10

8- Find files newer than dir3/file1.txt

find . -type f -newer dir3/file1.txt

9- Find all files except mp3’s. (!) is a logical NOT which negates (-iname “*.mp3”) expression

find . -type f ! -iname "*.mp3"

10- Find all text files and remove them using (-exec) option, whcih takes other commands, in this case “rm” command. The ‘{} \;’ symbols after “rm” are just the placeholder meaning the files from previews command.

find . -type f -iname "*.txt" -exec rm {} \;

11- Find all files larger than 1G

find . -size +1G

12- Find all shell script files and change permission to 0777 (rwx) for everyone (not good idea!)

find . -type f -iname "*.sh" -exec chmod 0777 {} \;

13- Find the text “hello world” with any text file using grep command

find . -iname "*.txt" -exec grep "hello world" -il {} \;

14- Using “|”, xargs and tar to backup all jpg files. xargs is a command that acts on the output of first command “find.” Then xargs passes the files to the tar command for compression.

find . -iname "*.jpg" | xargs tar -cvzf mybackup.tar.gz \;

15- Making incremental backup using -newer option, in order to backup any jpg file newer than the creation of last backup.

find . -newer mybackup.tar.gz -iname "*.jpg" | xargs tar -cvzf incrementBackup.tar.gz \;

Note: if you want to see the content of the backup file, just do..

tar -tf incrementBackup.tar.gz
Share This!

Add a Comment

Your email address will not be published.

Sign up for our Newsletter

Download "Google Search Pro"

Enter your email and stay on top of things,