Searching for Files in Linux Shell

Before you start

Objectives: Learn which two commands are commonly used to search for files in Linux by using shell.

Prerequisites: no prerequisites.

Key terms: command, files, find, file, firectory, fonts, locate, search, manula, start, list, type


 Find Command

The first command which is often used to search for files is the “find” command. This command is very useful for finding files with specific attributes. With the “find” command we have to specify the path that we will be searching for, and than we can specify other options. For example, let’s try and find all files that start with “man”. The current working directory in our case is “/home/cicnavi/Documents”. The command to do that is “find ./man*“. The star at the end denotes any character.

find Command 1

With “./” we specify that we want to search in current directory. The result actually gives us two files. The first “manual2” file is the original file, while the “manual2~” file is the backup file for “manaul2” file (the tilde at the end of the file denotes backup file). Let’s try and find all files that start with “le” in the “/bin” directory. The command to do that is “find /bin/le*

 find2

find Command 2

We have 5 files that start with “le” in the “/bin” directory. The “find” command will also return the name of the directory. For example, let’s try and find all files (and/or directories) that start with “font” in the “/etc” directory. The command is: “find /etc/fonts“.

 find3

find Command 3

Note that this command will list files and directories named “fonts”, and all directories and files inside of “fonts” directory. To only list directories, we can use the “-type d” argument. The command is “find /etc/fonts -type d“.

 find4

find Command 4

This command will list “font” directory and directories in it. To only list files we can use the “-type f” argument. The command is “find /etc/fonts -type f“.

 find5

find Command 5

With this command we have listed all files (no directories) inside the “fonts” directory.

Locate Command

The locate command is often used to search the file system and find out where certain file is. There are several versions of locate command. The original locate command showed us all files, even files that we don’t have permissions to see. The newer version of this command will take file permissions into account and it will not show us files that we don’t have permissions to see.

For example, let search for file named manual on our file system. To do that we will enter the command “locate manual“.

locate

locate Command

Note that the result gave us all files that have “manual” anywhere in its file name.