Linux locate, which and find Commands

All three commands allow the user to find files on their system. Each has different strength.

locate Command

The locate command (man page) is very fast since it builds a database for file searches and doesn’t have to walk all the directory trees every time. It does require an occasional maintenance update command but it is not a problem.

# Command format.
locate [options] [search string]

# Find all ".bashrc" files - providing partial search string.
$ locate bashrc
/etc/bash.bashrc
/etc/skel/.bashrc
/home/me/.bashrc
...

# Case insensitive search.
$ locate -i Bashrc

If you can’t find the expected information or you get old data, you will need to refresh the database that locate uses. The operation is typically fast.

$ sudo updatedb

which Command

This command (man page) will walk down the user’s $PATH variable to find the desired file. This is really handy if a script exists in multiple locations to see the one that will actually be executed.

# Print the current $PATH.
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

# Print first file in order specified by $PATH.
$ which man
/usr/bin/man

# Print all instances of file in order specified by $PATH.
$ which -a man
/usr/bin/man
/bin/man

Usually one of the executables is a symlink to the other one, but in some cases, you may have two versions of the same command installed in different locations or totally different commands using the same name.

find Command

The find command (man page) is a lot more powerful. You can filter your search criteria many more ways.

# Typical format: find [starting-point...]  [expression]

# Find all files in file system named "ftp". Don't show me directory "Permission denied" lines.
$ find / -name ftp -type f 2>/dev/null
/usr/lib/apt/methods/ftp
/var/lib/dpkg/alternatives/ftp

# Alternative way to not display the "Permission denied" lines. Filter with grep.
$ find / -name ftp -type f 2>&1 | grep -v "Permission denied"

# Find all directories in file system named "ftp". Don't show me directory "Permission denied" lines.
$ find / -name ftp -type d 2>/dev/null
/usr/share/doc/ftp

# Find all directories in file system named "ftp" (ignore case). Don't show me directory "Permission denied" lines.
$ find / -iname ftp -type d 2>/dev/null
/usr/share/doc/ftp
/usr/share/perl/5.34.0/Net/FTP
/usr/share/perl/5.34.0/CPAN/FTP

# Find all files/folders in this folder with permission of 755
$ find . -perm 755