Find the owner linux

UNIX / Linux Find File Owner Name

Q. How do I find out the name of file / directory owner under UNIX / Linux operating systems?

A. You can use ls -l command (list information about the FILEs) to find our the file / directory owner and group names.

The -l option is known as long format which displays Unix / Linux / BSD file types, permissions, number of hard links, owner, group, size, date, and filename. In some environments and UNIX versions / Linux distributions, providing the option –color (for GNU ls) or -G (FreeBSD ls) causes ls to highlight different types of files with different colors.

(Fig. 01: Linux file colors)

(Fig. 02: Understanding Linux / UNIX file colors code [ image credit wikipedia] )

How do I find out owner / group name for a file?

Type the ls -l command at a shell prompt:
$ ls -l filename
Sample output:

  • 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

  • -rw-r–r– : file mode
  • 1 – number of links
  • vivek – Owner name (if user name is not a known user, the numeric user id displayed)
  • admin – Group name (if group name is not a known group, the numeric group id displayed)
  • 2558 – number of bytes in the file (file size)
  • Jan 8 07:41 – abbreviated month, day-of-month file was
    last modified, hour file last modified, minute file last modified
  • filename – File name / pathname

ls -l file mode (permissions)

Quoting from the unix ls command man page – the file mode printed under the -l option consists of the entry type and the permissions. The entry type character describes the type of file, as follows:

Regular file.
b Block special file.
c Character special file.
d Directory.
l Symbolic link.
p FIFO.
s Socket.
w Whiteout.

The next three fields are three characters each: owner permissions, group permissions, and other permissions. Each field has three character positions:

  1. If r, the file is readable; if -, it is not readable.
  2. If w, the file is writable; if -, it is not writable.
  3. The first of the following that applies:
  • S : If in the owner permissions, the file is not executable and set-user-ID mode is set. If in the group permissions, the file is not executable and set-group-ID mode is set.
  • s : If in the owner permissions, the file is executable and set-user-ID mode is set. If in the group permissions, the file is executable and set group-ID mode is set.
  • x : The file is executable or the directory is searchable.
  • : The file is neither readable, writable, executable, nor set-user-ID nor set-group-ID mode, nor sticky.
Читайте также:  Windows удаление языков интерфейса
  • These next two apply only to the third character in the last group (other permissions).
    • T : The sticky bit is set (mode 1000), but not execute or search permission.
    • t : The sticky bit is set (mode 1000), and is search able or executable.

    See ls command man page for more information:
    $ man ls

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

    Источник

    Linux / Unix Find All The Files Owned By a Particular User / Group

    Linux / Unix Find All The Files Owned By a Particular User / Group

    Let us see how to use the find command to locate all files/folders owned by one or many users on Linux or Unix-like system.

    Find file owned by a group

    Tutorial details
    Difficulty level Easy
    Root privileges Yes
    Requirements Linux or Unix
    Est. reading time 2m

    Use the following syntax to find files owned by users(s) in Linux/Unix:
    find directory-location -group < group-name >-name < file-name >
    Where,

    • directory-location : Locate the file in this directory path.
    • -group : Find the file belongs to group-name.
    • -name : The file name or a search pattern

    In this example, locate or find all files belongs to a group called “ftpusers” in the /home directory:
    # find /home -group ftpusers
    To find all *.c file belongs to a group called “ftpusers” in /data/project directory, run:
    # find /data/project -group ftpusers -name «*.c»
    OR do case insensitive search:
    # find /data/project -group ftpusers -iname «*.c»

    Find all *.mp4 files by group vivek

    Find file owned by user

    The syntax is:
    find directory-location -user < username >-name < file-name >
    Where,

    • directory-location : Locate files or directories in this directory location.
    • -user < user-name >: Find the file belongs to user.
    • -name : File name or pattern.

    In this example, locate or find all file belongs to a user called “vivek” in /var directory:
    # find /var -user vivek
    To find all *.pl (perl files) file belongs to a user called “vivek” in /var/www directory, enter:
    # find /var/www -user vivek -name «*.pl»

    • 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

    How to find files by users vivek and wendy

    ### match files only ##
    # find / -type f -user vivek -o -user wendy
    ### match dirs only ##
    # find / -type d -user vivek -o -user wendy

    Conclusion

    You just learned how to find all of the files created by a particular user/group and display them to the screen. For more info see find command man page.

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

    Источник

    Find the group name of the folder in UNIX / Linux

    Find the group name of the folder in UNIX

    The procedure to discover the group name of the folder in UNIX and Linux is as follows:

    1. Open the terminal application
    2. Run command on the folder: ls -ld /path/to/folder
    3. To find owner and group of a directory named /etc/ use: stat /etc/
    4. Use the Linux and Unix GUI file manager to locate the group name of the folder

    Let us see some examples in details.

    How to find owner and group of a directory in Linux

    Say you want to find the group name of the $HOME/Downloads/ folder, run:
    ls -ld $HOME/Downloads/
    Second method is to run the stat command as follows:
    stat /etc/
    stat /home/vivek/Downloads/
    Look for GID (group ID) and UID (User ID):

    Find the group name of the folder in Linux or UNIX using GUI

    nautilus is a file manager, designed for the GNOME 3 desktop.

    • Start the nautilus.
    • Choose the folder.
    • Right click it.
    • Select Properties and click on the Permissions tab

    How to check ownership of directory in Linux or Unix

    Another option is to just run the following stat command:
    stat -c «User:%U Group:%G» /path/to/dir/
    stat -c «User:%U Group:%G» /etc/
    Sample outputs:

    • 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

    One can pass the -c option for the specified FORMAT instead of the default. In this example:

    • %U – user name of owner
    • %G – group name of owner

    Conclusion

    One can use the stat command to display file status including owner and group names. The ls command provides information easily too. Finally, one can use the KDE or GNOME desktop file manager to obtain the group and owner names on Linux and Unix-like systems.

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

    Источник

    Команда find в Linux – мощный инструмент сисадмина

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

    Команда find – это невероятно мощный инструмент, позволяющий искать файлы не только по названию, но и по:

    • Дате добавления.
    • Содержимому.
    • Регулярным выражениям.

    Данная команда будет очень полезна системным администраторам для:

    • Управления дисковым пространством.
    • Бэкапа.
    • Различных операций с файлами.

    Команда find в Linux производит поиск файлов и папок на основе заданных вами критериев и позволяет выполнять действия с результатами поиска.

    Синтаксис команды find:

    • directory-to-search (каталог поиска) – это отправной каталог, с которой find начинает поиск файлов по всем подкаталогам, которые находятся внутри. Если не указать путь, тогда поиск начнется в текущем каталоге;
    • criteria (критерий) – критерий, по которым нужно искать файлы;
    • action (действие) – что делать с каждым найденным файлом, соответствующим критериям.

    Поиск по имени

    Следующая команда ищет файл s.txt в текущем каталоге:

    • . (точка) – файл относится к нынешнему каталогу
    • -name – критерии по которым осуществляется поиск. В данном случае поиск по названию файла.

    В данном случае критерий -name учитывает только символы нижнего регистра и файл S.txt не появиться в результатах поиска. Чтобы убрать чувствительность к регистру необходимо использовать –iname.

    Для поиска всех изображений c расширением .png нужно использовать шаблон подстановки *.png:

    Можно использовать название каталога для поиска. Например, чтобы с помощью команды find найти все png изображения в каталоге home:

    Если выдает слишком много ошибок в отказе разрешения, тогда можно добавить в конец команды – 2> /dev/null. Таким образом сообщения об ошибках будут перенаправляться по пути dev/null, что обеспечит более чистую выдачу.

    Поиск по типу файла

    Критерий -type позволяет искать файлы по типу, которые бывают следующих видов:

    • f – простые файлы;
    • d – каталоги;
    • l – символические ссылки;
    • b – блочные устройства (dev);
    • c – символьные устройства (dev);
    • p – именованные каналы;
    • s – сокеты;

    Например, указав критерий -type d будут перечислены только каталоги:

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

    Допустим, что вам необходимо найти все большие файлы. Для таких ситуаций подойдет критерий -size.

    • «+» — Поиск файлов больше заданного размера
    • «-» — Поиск файлов меньше заданного размера
    • Отсутствие знака означает, что размер файлов в поиске должен полностью совпадать.

    В данном случае поиск выведет все файлы более 1 Гб (+1G).

    Единицы измерения файлов:

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

    Критерий -empty позволяет найти пустые файлы и каталоги.

    Поиск времени изменения

    Критерий -cmin позволяет искать файлы и каталоги по времени изменения. Для поиска всех файлов, измененных за последний час (менее 60 мин), нужно использовать -60:

    Таким образом можно найти все файлы в текущем каталоге, которые были созданы или изменены в течение часа (менее 60 минут).

    Для поиска файлов, которые наоборот были изменены в любое время кроме последнего часа необходимо использовать +60.

    Поиск по времени доступа

    Критерий -atime позволяет искать файлы по времени последнего доступа.

    Таким образом можно найти файлы, к которым не обращались последние полгода (180 дней).

    Поиск по имени пользователя

    Опция –user username дает возможность поиска всех файлов и каталогов, принадлежащих конкретному пользователю:

    Таким образом можно найти все файлы пользователя tisha в каталоге home, а 2>/dev/null сделает выдачу чистой без ошибок в отказе доступа.

    Поиск по набору разрешений

    Критерий -perm – ищет файлы по определенному набору разрешений.

    Поиск файлов с разрешениями 777.

    Операторы

    Для объединения нескольких критериев в одну команду поиска можно применять операторы:

    Например, чтобы найти файлы размером более 1 Гбайта пользователя tisha необходимо ввести следующую команду:

    Если файлы могут принадлежать не только пользователю tisha, но и пользователю pokeristo, а также быть размером более 1 Гбайта.

    Перед скобками нужно поставить обратный слеш «\».

    Действия

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

    • -delete — Удаляет соответствующие результатам поиска файлы
    • -ls — Вывод более подробных результатов поиска с:
      • Размерами файлов.
      • Количеством inode.
    • -print Стоит по умолчанию, если не указать другое действие. Показывает полный путь к найденным файлам.
    • -exec Выполняет указанную команду в каждой строке результатов поиска.

    -delete

    Полезен, когда необходимо найти и удалить все пустые файлы, например:

    Перед удалением лучше лишний раз себя подстраховать. Для этого можно запустить команду с действием по умолчанию -print.

    Данное действие является особенным и позволяет выполнить команду по вашему усмотрению в результатах поиска.

    • command – это команда, которую вы желаете выполнить для результатов поиска. Например:
      • rm
      • mv
      • cp
    • <> – является результатами поиска.
    • \; — Команда заканчивается точкой с запятой после обратного слеша.

    С помощью –exec можно написать альтернативу команде –delete и применить ее к результатам поиска:

    Другой пример использования действия -exec:

    Таким образом можно скопировать все .jpg изображения в каталог backups/fotos

    Заключение

    Команду find можно использовать для поиска:

    • Файлов по имени.
    • Дате последнего доступа.
    • Дате последнего изменения.
    • Имени пользователя (владельца файла).
    • Имени группы.
    • Размеру.
    • Разрешению.
    • Другим критериям.

    С полученными результатами можно сразу выполнять различные действия, такие как:

    • Удаление.
    • Копирование.
    • Перемещение в другой каталог.

    Команда find может сильно облегчить жизнь системному администратору, а лучший способ овладеть ей – больше практиковаться.

    Источник

    Читайте также:  What are the windows server versions
  • Оцените статью