When you are working with the command line in Linux you need to know how to find files quickly. There are few utilities that can get the job done but you should know how to use them and when to use them.
One among such utility is locate command and in this tutorial, we will walk through how to install locate command if not already installed and see how to use them effectively in Linux.
How to Install locate Command in Linux
Before using the locate command you should check if it is installed in your machine. A locate command comes with GNU findutils or GNU mlocate packages. You can simply run the following command to check if locate is installed or not.
$ which locate
If locate is not installed by default then you can run the following commands to install.
$ sudo yum install mlocate [On CentOS/RHEL/Fedora] $ sudo apt install mlocate [On Debian/Ubuntu/Mint]
Once the installation is completed you need to run the following command to update the locate database to quickly get the file location. That’s how your result is faster when you use the locate command to find files in Linux.
$ sudo updatedb
The mlocate db file is located at /var/lib/mlocate/mlocate.db.
$ ls -l /var/lib/mlocate/mlocate.db
A good place to start and get to know about locate command is using the man page.
$ man locate
How to Use locate Command to Find Files Faster in Linux
To search for any files simply pass the file name as an argument to locate command.
$ locate .bashrc
If you wish to see how many matched items instead of printing the location of the file you can pass the -c
flag.
$ sudo locate -c .bashrc
By default locate command is set to be case sensitive. You can make the search to be case insensitive by using the -i
flag.
$ sudo locate -i file1.sh
You can limit the search result by using the -n
flag.
$ sudo locate -n 3 .bashrc
When you delete a file and if you did not update the mlocate database it will still print the deleted file in output. You have two options now either to update mlocate db periodically or use -e
flag which will skip the deleted files.
$ locate -i -e file1.sh
You can check the statistics of the mlocate database by running the following command.
$ locate -S
If your db file is in a different location then you may want to use -d
flag followed by mlocate db path and filename to be searched for.
$ locate -d [ DB PATH ] [ FILENAME ]
Sometimes you may encounter an error, you can suppress the error messages by running the command with the -q
flag.
$ locate -q [ FILENAME ]
That’s it for this article. We have shown you all the basic operations you can do with locate command. It will be a handy tool for you when working on the command line.