As the name suggests, the locate command in Linux is used for locating (searching) a file. It has the following syntax:
locate [options] filename
While it is real simple to use the locate command, it comes with lots of ifs and buts. For starter, if it doesn’t find a file, it doesn’t necessarily mean that the file does not exist on the system.
Don’t be confused just now. I’ll explain how the locate command works and how can you use it for finding files.
Using locate command in Linux
The locate command works on an index i.e. a database of file locations. When you use the command, it refers to this index instead of searching the entire filesystem. This is the reason why locate is super quick at finding files in Linux.
Some Linux distributions automatically index the entire filesystem on a regular basis. You can also manually build this index (i'll show it to you later in this article).
Using locate command is dead simple. You just have to specify the file name:
The result will show all the places where the file you specified was found.
[email protected]:~$ locate desktop.iso /home/abhishek/desktop.iso
The best part is that you don’t need to be in the certain directory to find the file. Remember, locate command doesn’t search the filesystem but the index. This is why you don’t need to specify a path or directory while looking for files.
You can also perform a case-insensitive search by using the -i option:
[email protected]:~$ locate -i desktop.iso /home/abhishek/desktop.iso /home/abhishek/Downloads/Desktop.iso
Keep in mind that the result may show all the files that have the search term in their name.
[email protected]:~$ locate -i desktop /home/abhishek/eoan-desktop-amd64.iso /home/abhishek/Bionic-Desktop-amd64.iso /home/abhishek/desktop.iso /home/abhishek/Downloads/Desktop.iso
You may also use regex with locate:
locate -r regex_expression
Using updatedb to create your own index for locate command
This is just for informational purpose and I don’t think you would need to use it.
If you want to create an index of the present directory (and its subdirectories), you can use the updatedb command like this:
updatedb -l0 -U my_directory -o index_file
Once you have created this index file, you can ask locate command to explicitly use this index:
locate -d index_file file_name
Is locate better than the find command?
If you want to search for files in a directory structure that doesn’t change much, locate command is a good option. It is super quick as well.
But the find command gives you a lot of option, specially for performing complex search options.
Both commands have their usage. In my opinion, if you are feeling lazy and want a quick result, use locate. If the result is not of your liking, switch to find command.
What do you think?