Linux find all dir

How To Find a Directory On Linux Based System

I just switched from MS-Windows server admin to Debian Linux server system administration roles. I need to find a directory called project.images. I was also told that the locate command is the simplest and quickest way to find the locations of files and directories on Linux. But the locate command is not working out for me. How do I find project.images directory using command-line options only?

Tutorial details
Difficulty level Easy
Root privileges No
Requirements find command on Linux or macOS/Unix
Est. reading time 5m

You need to use find command. It is used to locate files on Linux or Unix-like system. The locate command will search through a prebuilt database of files generated by updatedb.

The find command will search live file-system for files that match the search criteria.

How to find a directory on Linux

The find command syntax is:
find /where/to/look/up criteria action
find /dir/path/look/up criteria action
find /dir/path/look/up -name «dir-name-here»
find /dir/path/look/up -name «pattern»
find /dir/path/look/up -name «dir-name-here» -print
find /dir/path/look/up -name «dir-name-here»
find / -name «dir-name-here»
find / -type d -name «dir-name-here»
find / -type d -name «dir-name-here» 2>/dev/null

Linux find directory command

The following example will show all files in the current directory and all subdirectories:

Finding a directory

To find a directory called apt in / (root) file system, enter:

Alert: When searching / (root) file system, you need to run the find command as root user.

Dealing with “Permission denied error messages” on Linux

Find will show an error message for each directory/file on which you don’t have read permission

How to find a directory named Documents on Linux?

Type the following command to search for Documents directory in your $HOME dir:
$ find $HOME -type d -name Documents
Sample outputs:

Getting a detailed list of files/dirs

Pass the -ls to list current file in ls command output format:

How do I list only directories?

Just find directories and skip file names pass the -type d option as follows:

Replace -name option with -iname as follows:

The patterns ‘apt’ match the directory names ‘apt’, ‘APT’, ‘Apt’, ‘apT’, etc.

How do I find a directory called project.images?

Type any one of the following command:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

A note about locate command

See also
  • All find command examples from our /faq/ sections.
  • Find command man page

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Why don’t you run updatedb and then locate and again you’ll have “simplest and quickest way to find the locations of files and directories on Linux”.

updatedb will update your database.

That only helps for semi-permanent files since it only checks periodically to update the updatedb database. For files that were created recently it will not be found.

Find is a great tool that i use a lot.
You could have talk about the -exec switch wich allows you to process the outpout. ie : find and delete all file in ./ that haven’t been modified since 90 day:

Anyway, great job on this website, keep it on!

I have to second that updatedb is the way to go for a novice linux user. No worries about syntax and whatnot. Its also very useful for when you need to do multiple scans since you only traverse the filesystem once.

In regards to -exec, you should be using -execdir when available due to some security implications… and the above rm -rf is somewhat dangerous since find by default traverses from the top down. Delete would be a much safer (and faster!!) operation than-exec rm.

I have to agree with your update, rm -Rf is maybe too dangerons to use for novice users.

I did not know -execdir wich seems to be very usefull.

Thank you for that update =)

Great article. so useful. since I don’t have root, I get very verbose “no permission” output that is useless and I have to find the actual location through all the muck. Is there a way to only print found paths? Thanks so much for this article!

All those “no permission” messages should be on stderr while the information you want is on stdout. Both stderr and stdout default to printing on the controlling terminal. Tacking “> stdoutfile” on the end of the command would separate them, leaving all the unwanted noise on the terminal and putting the good stuff in stdoutfile. It would make more sense to redirect stderr to /dev/null (throwing it away) and leaving the useful output on the controlling terminal, but that would require finding the instructions for redirecting stderr in the shell docs (again).

To avoid seeing stderr messages, just use something like this:

Источник

Команда find в Linux

Очень важно уметь вовремя и очень быстро найти нужную информацию в системе. Конечно, все современные файловые менеджеры предлагают отличные функции поиска, но им не сравнится с поиском в терминале Linux. Он намного эффективнее и гибче обычного поиска, вы можете искать файлы не только по имени, но и по дате добавления, содержимому, а также использовать для поиска регулярные выражения. Кроме того, с найденными файлами можно сразу же выполнять необходимые действия.

В этой статье мы поговорим о поиске с помощью очень мощной команды find Linux, подробно разберем ее синтаксис, опции и рассмотрим несколько примеров.

Основная информация о Find

Find — это одна из наиболее важных и часто используемых утилит системы Linux. Это команда для поиска файлов и каталогов на основе специальных условий. Ее можно использовать в различных обстоятельствах, например, для поиска файлов по разрешениям, владельцам, группам, типу, размеру и другим подобным критериям.

Утилита find предустановлена по умолчанию во всех Linux дистрибутивах, поэтому вам не нужно будет устанавливать никаких дополнительных пакетов. Это очень важная находка для тех, кто хочет использовать командную строку наиболее эффективно.

Команда find имеет такой синтаксис:

find [ папка] [ параметры] критерий шаблон [действие]

Папка — каталог в котором будем искать

Параметры — дополнительные параметры, например, глубина поиска, и т д

Критерий — по какому критерию будем искать: имя, дата создания, права, владелец и т д.

Шаблон — непосредственно значение по которому будем отбирать файлы.

Основные параметры команды find

Я не буду перечислять здесь все параметры, рассмотрим только самые полезные.

  • -P никогда не открывать символические ссылки
  • -L — получает информацию о файлах по символическим ссылкам. Важно для дальнейшей обработки, чтобы обрабатывалась не ссылка, а сам файл.
  • -maxdepth — максимальная глубина поиска по подкаталогам, для поиска только в текущем каталоге установите 1.
  • -depth — искать сначала в текущем каталоге, а потом в подкаталогах
  • -mount искать файлы только в этой файловой системе.
  • -version — показать версию утилиты find
  • -print — выводить полные имена файлов
  • -type f — искать только файлы
  • -type d — поиск папки в Linux

Критерии

Критериев у команды find в Linux очень много, и мы опять же рассмотрим только основные.

  • -name — поиск файлов по имени
  • -perm — поиск файлов в Linux по режиму доступа
  • -user — поиск файлов по владельцу
  • -group — поиск по группе
  • -mtime — поиск по времени модификации файла
  • -atime — поиск файлов по дате последнего чтения
  • -nogroup — поиск файлов, не принадлежащих ни одной группе
  • -nouser — поиск файлов без владельцев
  • -newer — найти файлы новее чем указанный
  • -size — поиск файлов в Linux по их размеру

Примеры использования

А теперь давайте рассмотрим примеры find, чтобы вы лучше поняли, как использовать эту утилиту.

1. Поиск всех файлов

Показать все файлы в текущей директории:

2. Поиск файлов в определенной папке

Показать все файлы в указанной директории:

Искать файлы по имени в текущей папке:

Не учитывать регистр при поиске по имени:

find . -iname «test*»

3. Ограничение глубины поиска

Поиска файлов по имени в Linux только в этой папке:

find . -maxdepth 1 -name «*.php»

4. Инвертирование шаблона

Найти файлы, которые не соответствуют шаблону:

find . -not -name «test*»

5. Несколько критериев

Поиск командой find в Linux по нескольким критериям, с оператором исключения:

find . -name «test» -not -name «*.php»

Найдет все файлы, начинающиеся на test, но без расширения php. А теперь рассмотрим оператор ИЛИ:

find -name «*.html» -o -name «*.php»

6. Несколько каталогов

Искать в двух каталогах одновременно:

find ./test ./test2 -type f -name «*.c»

7. Поиск скрытых файлов

Найти скрытые файлы:

8. Поиск по разрешениям

Найти файлы с определенной маской прав, например, 0664:

find . type f -perm 0664

Найти файлы с установленным флагом suid/guid:

find / -perm 2644

find / -maxdepth 2 -perm /u=s

Поиск файлов только для чтения:

find /etc -maxdepth 1 -perm /u=r

Найти только исполняемые файлы:

find /bin -maxdepth 2 -perm /a=x

9. Поиск файлов в группах и пользователях

Найти все файлы, принадлежащие пользователю:

find . -user sergiy

Поиск файлов в Linux принадлежащих группе:

find /var/www -group developer

10. Поиск по дате модификации

Поиск файлов по дате в Linux осуществляется с помощью параметра mtime. Найти все файлы модифицированные 50 дней назад:

Поиск файлов в Linux открытых N дней назад:

Найти все файлы, модифицированные между 50 и 100 дней назад:

find / -mtime +50 –mtime -100

Найти файлы измененные в течении часа:

11. Поиск файлов по размеру

Найти все файлы размером 50 мегабайт:

От пятидесяти до ста мегабайт:

find / -size +50M -size -100M

Найти самые маленькие файлы:

find . -type f -exec ls -s <> \; | sort -n -r | head -5

find . -type f -exec ls -s <> \; | sort -n | head -5

12. Поиск пустых файлов и папок

find /tmp -type f -empty

13. Действия с найденными файлами

Для выполнения произвольных команд для найденных файлов используется опция -exec. Например, выполнить ls для получения подробной информации о каждом файле:

find . -exec ls -ld <> \;

Удалить все текстовые файлы в tmp

find /tmp -type f -name «*.txt» -exec rm -f <> \;

Удалить все файлы больше 100 мегабайт:

find /home/bob/dir -type f -name *.log -size +100M -exec rm -f <> \;

Выводы

Вот и подошла к концу эта небольшая статья, в которой была рассмотрена команда find. Как видите, это одна из наиболее важных команд терминала Linux, позволяющая очень легко получить список нужных файлов. Ее желательно знать всем системным администраторам. Если вам нужно искать именно по содержимому файлов, то лучше использовать команду grep.

Источник

Читайте также:  Создам свою сборку windows
Оцените статью