Linux: How to find if filenames of a directory exist in another directory

Recently i had the following issue, i needed to find if filenames in a directory exist in other directories, in this case find command was…

Linux: How to find if filenames of a directory exist in another directory
Photo by Jamie Street on Unsplash

Recently i had the following issue, i needed to find if filenames in a directory exist in other directories, in this case find command was my friend!

How it works

I used the following command, lets break it down

find . -type f -exec basename {} \; | xargs -I {} find /etc/httpd -type f -name {}

The first find command prints only the filenames found without the path, those are the filenames we want to check if exist in another directory

find . -type f -exec basename {} \; 
ca.crt-2 
local.crt 
local.key 
server-ca.crt 
ca.crt 
ca-bundle.crl

Next we use | xargs -I {} to pipe the filenames to the second find command

| xargs -I {} find /etc/httpd -type f -name {}

This find command will search for each filename if exists in /etc/httpd in my case the output was the following because 3 of the filenames exist in both directories!

/etc/httpd/conf/ssl.crt/server-ca.crt 
/etc/httpd/conf/ssl.crt/ca.crt 
/etc/httpd/conf/ssl.crl/ca-bundle.crl

Note: This method does not provide a way to find if the content of the files is the same but rather checks only if the filenames match!

Conclusion

The only conclusion is how much i love bash for those little cool tricks that can make your life easier! bash is super cool and can enhance your life as a sysadmin, devops or just human being!