Share Pin 0 Shares

Per Nick the Geek suggestion on last post, today will be talking about the find command. If you have any suggestions for next tricks please don’t forget to leave them in the comment section 🙂

According with find command manual, it searches for files in a directory hierarchy. Besides that, I would say it is a powerful ally which allows you to do really amazing black magics in your scripts.

If you lost the first Bash Trick, you can read it here: checking whether a file exists.

1. Find a specific file

For example, if you want to find all files called wp-config.php in /var/www directory, you can use the below command:

find /var/www/ -name wp-config.php

Thus, it will search for the wp-config.php on all directories of the /var/www structure.

2. Find a specific file limiting the levels of directories

Before start this step, a good thing to keep in mind is that find command works recursively. In other words, if you run a find in /var/www, it will go through all the files and directories available in /var/www.

That said, let’s assume we know that all wp-config.php files are in the next level of directory than the one we are searching. Thus, we could determine how many levels of directories the find command will go through:

find /var/www/ -name wp-config.php -maxdepth 2

The above command will search for the file only at the target directory (/var/www – depth 1) and at the next level directories (/var/www/example1.com, /var/www/example2.com – depth 2).

This way, it is possible to reduce the search and optimize your bash script.

3. Find and remove old files

If you want to remove only files created more than 15 days ago from /tmp directory, run:

find /tmp/ -ctime +15 -type f -exec rm {} \;

This way, all the files created more than 15 days ago will be removed. The -type f param makes the find search only for files, avoiding directories and symbolic links. To find only for directories, use d instead of f on -type value.

Also, it is possible to check the last modification time or access time using the –mtime and –atime, respectively, instead of –ctime.

4. Find and remove files per extension

Finally, it is possible to remove files using a specific extension. For example, if you want to remove all .php files from /var/www directory, please run:

find /var/www/*.php -type f -exec rm {} \;

So it will remove all PHP files inside of /var/www directory and their sub-directories.

If you have any difficulties with find command, please comment and I will be more than happy to help you addressing them.

Please don’t forget to share it on your social media outlets!

See you in few days 🙂